In Go, the idiomatic way to convert a string to an integer is by using strconv.Atoi()
or strconv.ParseInt()
.
If you’re working with command-line arguments like flag.Arg(n)
, you can convert it like this:
import (
"fmt"
"strconv"
)
str := "42"
num, err := strconv.Atoi(str)
if err != nil {
// handle error
}
fmt.Println(num)
This is the recommended approach for golang string to int
conversion.