How to convert a string to an integer in Go

This article considers a few different ways to convert a string to an integer in Go.

The easiest way to convert a string to an integer in Go is by using the strconv.Atoi method. It takes a string and returns the converted integer or an error if the conversion fails.

package main

import (
	"fmt"
	"log"
	"strconv"
)

func main() {
	str := "500"
	i, err := strconv.Atoi(str)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(i) // 500
}

You can also use the strconv.ParseInt method if you want to convert a string to a integer in a number base other than 10. As mentioned in the docs, strconv.Atoi is actually equivalent to strconv.ParseInt(s, 10, 0) converted to the int type.

The first argument to ParseInt is the string to be converted. The second is the number base (0, 2 to 36), and the third is the integer type that the result must fit into (0, 8, 16, 32, and 64). 0 is equivalent to int, 8 to int8, and so on.

package main

import (
	"fmt"
	"log"
	"strconv"
)

func main() {
	str := "500"
	i, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(i) // 500
}

Another method that may come in handy is fmt.Sscanf. This method scans the first string argument, and stores each space-separated value in the string into successive arguments as determined by the format string (second argument).

package main

import (
	"fmt"
	"log"
)

func main() {
	str := "500 1000"
	var i, j int
	_, err := fmt.Sscanf(str, "%d%d", &i, &j)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(i, j) // 500 1000
}

This method is great if you want to extract a number from a string for example.

package main

import (
	"fmt"
	"log"
)

func main() {
	str := "http://localhost:1313"
	var i int
	_, err := fmt.Sscanf(str, "http://localhost:%d", &i)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(i) // 1313
}

Wrap up

In this article, we considered three ways to convert a string to an integer in Go. The strconv.Atoi method should suffice for most use cases, but it’s nice to know that there are other options as well. If you have any further contribution, please leave a comment below.

Thanks for reading, and happy coding!