Convert strings to integers

Avatar of the author Willem Schots
17 Jul, 2024
~2 min.
RSS

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.

main.go
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:

main.go
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.

Make privacy claims you can back up

Join 800+ subscribers.
One email every few weeks.

I share what I learn building privacy-friendly systems. From confidential computing to Verbond and the occasional Go tip or trick. You can unsubscribe at any time.

A photo of Willem

Written by Willem Schots

I help teams prove what happens to their users' data, and I'm building Verbond, which shows where data can go before third-party code runs.

This site started as a place to learn Go. Most posts are now about privacy-friendly and verifiable systems, with the occasional Go post in between.

Want to talk about your system? Book a 30-minute call, or follow me on Bluesky and LinkedIn.