How to Convert string to integer type in Go?
Like most modern languages, Golang includes strings as a built-in type. Let's take an example, you may have a string that contains a numeric value "100". However, because this value is represented as a string, you can't perform any mathematical calculations on it. You need to explicitly convert this string type into an integer type before you can perform any mathematical calculations on it. In order to convert string to integer type in Golang, you can use the following methods.
Atoi() Function
You can use the strconv package's Atoi() function to convert the string into an integer value. Atoi stands for ASCII to integer. The Atoi() function returns two values: the result of the conversion, and the error (if any).
Syntax
func Atoi(s string) (int, error)
Example
package main
import (
"fmt"
"strconv"
"reflect"
)
func main() {
strVar := "100"
intVar, err := strconv.Atoi(strVar)
fmt.Println(intVar, err, reflect.TypeOf(intVar))
}
Output
100 <nil> int
ParseInt() Function
ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i. This function accepts a string parameter, convert it into a corresponding int type based on a base parameter. By default, it returns Int64 value.Syntax
func ParseInt(s string, base int, bitSize int) (i int64, err error)
Example
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
strVar := "100"
intVar, err := strconv.ParseInt(strVar, 0, 8)
fmt.Println(intVar, err, reflect.TypeOf(intVar))
intVar, err = strconv.ParseInt(strVar, 0, 16)
fmt.Println(intVar, err, reflect.TypeOf(intVar))
intVar, err = strconv.ParseInt(strVar, 0, 32)
fmt.Println(intVar, err, reflect.TypeOf(intVar))
intVar, err = strconv.ParseInt(strVar, 0, 64)
fmt.Println(intVar, err, reflect.TypeOf(intVar))
}
Output
100 <nil> int64
100 <nil> int64
100 <nil> int64
100 <nil> int64
Using fmt.Sscan
The fmt package provides sscan() function which scans string argument and store into variables. This function read the string with spaces and assign into consecutive Integer variables.
Example
package main
import (
"fmt"
"reflect"
)
func main() {
strVar := "100"
intValue := 0
_, err := fmt.Sscan(strVar, &intValue)
fmt.Println(intValue, err, reflect.TypeOf(intValue))
}
Output
100 <nil> int
Most Helpful This Week
Example: How to use ReadFull from IO Package in Golang?Add N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-timeGet Year, Month, Day, Hour, Min and Second from current date and time.Example to use Weekday and YearDay functionHow do you write multi-line strings in Go?How to find the type of the variable by different ways in Golang?How to create Map using the make function in Go?Simple function with return value in GolangHow to Decode or Unmarshal bi-dimensional array of integers?How to get first and last element of slice in Golang?