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.
I usually use strconv.Atoi()
when converting strings to integers in Go especially when grabbing CLI args with flag.Arg(n)
.
num, err := strconv.Atoi(str)
Just don’t forget the error check, Go won’t let you skip it, and honestly, it’s saved me more than once from crashing apps.
In Go, I prefer strconv.ParseInt()
if I need a bit more control, like specifying the base or bit size. It’s slightly more flexible than Atoi()
:
num, err := strconv.ParseInt("42", 10, 64)
This comes in handy when you’re parsing non-decimal strings or targeting specific int types.
I ran into this when parsing config values from a file. At first, I used fmt.Sscanf
, but quickly switched to strconv.Atoi()
, way more reliable and idiomatic in Go.
If you’re dealing with flags or user input, Atoi()
is your friend. Just make sure to handle the error properly!