Converting String to integer in GoLang

String and integer are converted at times when needed and it is one of the most common forms of type conversion that happens in programming. In this post, we will cover string to integer conversion in GoLang.

Required imports

The strconv package is required for this conversion. So we need to import it.

import "strconv"

The strconv package is a string conversion package that can do many different conversions.

The Atoi method

The Atoi method simply converts a string consisting of numeric characters into an integer. Here is an example showing the Atoi method in use.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	v := "42"
	i, _ := strconv.Atoi(v)
	fmt.Println(i)    // 42       
}

This method is a special case for the ParseInt method shown below.

The Parseint method

The Parseint method is another method that is inside the strconv package. It can do the same conversion in a faster way.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	v := "213"
	i, _ := strconv.ParseInt(v, 10, 64)
	fmt.Println(i)   // 213   
}

It can be daunting to see that a simple conversion function taking many arguments but the Atoi method is equivalent to a specialized version of the ParseInt function ParseInt(s, 10, 0). The ParseInt method is the more generic method which has a function signature like follows:

func ParseInt(s string, base int, bitSize int) (i int64, err error)

As can be seen, the function takes two other arguments the base and bitSize. The base is the numeric base to which the string is being converted. Base-10 is the decimal while the Base-2 is binary. The bitSize is the size of the int we must return. E.g. setting bitSize to 32 will return a 32-bit integer or simply int32.

The Sscan and Sscanf method

The Sscan function is used when we want to parse the int from user input. Here is an example showing the Sscan method.

package main

import "fmt"
import "flag"

func main() {

	flag.Parse()
	s := flag.Arg(0)

	var i int

	_, e := fmt.Sscan(s, &i)

	if e != nil {
		fmt.Println(e)
	}

	fmt.Println("i is:", i)
}

When provided input via the CLI it outputs correctly.

The Sscan Method
The Sscan Method

The Sscanf method can be used to parse complex strings of different layouts.

package main

import "fmt"

func main() {
	s := "user:0456"     // string we want to parse
	var i int
	if _, err := fmt.Sscanf(s, "user:%4d", &i); err == nil {      // the layout is user:%4d
		fmt.Println(i) //
	}
}

This method parses the layout correctly. The output will be:

Go Sscanf Method
Go Sscanf Method

As can be seen, there are many ways we can convert string to integers in GoLang.