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
How to delete or remove element from a Map?How to replace emoji characters in string using regex in Golang?Different ways to validate JSON stringFind element in a slice and move it to first position?How to verify a string only contains letters, numbers, underscores, and dashes in Golang?Example: Split, Join, and Equal from BYTES PackageHow to split a string on white-space?How to use Ellipsis (...) in Golang?How to declare empty Map in Go?User Defined Function Types in Golang