Senior
How to convert a string to a number in Go?
sobes.tech AI
Answer from AI
In Go, functions from the strconv package are used to convert strings to numbers. Depending on the type of number, you can use:
strconv.Atoi— to convert a string toint.strconv.ParseInt— to convert to an integer with specified base and size.strconv.ParseFloat— for floating-point numbers.
Example of converting a string to int:
package main
import (
"fmt"
"strconv"
)
func main() {
s := "12345"
num, err := strconv.Atoi(s)
if err != nil {
fmt.Println("Conversion error:", err)
return
}
fmt.Println("Number:", num)
}
For more flexible control (for example, if you need to specify the base or size), you can use ParseInt:
num64, err := strconv.ParseInt(s, 10, 64) // base 10, 64-bit integer