In some languages you can cast between strings and integers directly. This is not the case in Go, in Go you will need to parse your strings to convert them to integers.
This snippet will show you how to use the strconv package in the standard library to parse strings. This package includes a variety of functions to help you convert between string and numeric types.
Using strconv.Atoi
The simplest way to convert a string to an integer in Go is by using the strconv.Atoi function. “Atoi” stands for “ASCII to integer”, based on the C function of the same name.
This function is an alias for strconv.ParseInt which you will see later. strconv.Atoi assumes a base of 10 and a bit size of 0.
package main
import (
"fmt"
"strconv"
)
func main() {
s := "12345"
i, err := strconv.Atoi(s)
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Println("integer:", i)
}
}
In this example, strconv.Atoi takes the string s and attempts to convert it to an integer. If the conversion fails, it returns an error.
Using strconv.ParseInt
For more control over the conversion, you can use strconv.ParseInt. This function allows you to specify the base and the bit size of the resulting integer. Here’s an example:
package main
import (
"fmt"
"strconv"
)
func main() {
s := "0101" // 5 in binary
i, err := strconv.ParseInt(s, 2, 64)
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Println("integer:", i)
}
}
In this example, strconv.ParseInt parses string s as a binary integer (base 2). The returned value will always be 64 bits, but only bits up to the provided bit size will be set.
If you want to parse unsigned integers, use strconv.ParseUint instead.
Error handling
Don’t forget to handle your errors. Depending on the origin of the string, there is no guarantee that it will contain a valid integer.
In the above examples, we just print the errors to stdout. In real apps you probably want to log them, show an error to users or handle them in a different way.
Career choice: Learn skills to mitigate the upcoming AI privacy disaster*
Join 800+ devs reading my newsletter
*Everyone and their mother is sending sensitive data to AI systems with little concern for their privacy. If you read the fineprint, vendors and platforms actually offer very little guarantees. It's a matter of time before it goes wrong.
From March 2026 onwards, I'll be writing about development of verifiably-secure services using OpenPCC.