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
Most Helpful This Week
Sierpinski triangle in Go Programming LanguageGolang download image from given URLAnonymous Functions in GolangHow to count number of repeating words in a given String?How to get first and last element of slice in Golang? How can I convert a string variable into Boolean, Integer or Float type in Golang?How to wait for Goroutines to Finish Execution?Print index and element or data from Array, Slice and MapHow to check if a string contains a white space in Golang?Convert specific UTC date time to PST, HST, MST and SGT