How do you convert a string to an integer in Go?

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.