Every language has it’s ways of converting data types. One of the most common data types to convert between is that of strings (string) and integers (int).

If you’ve ever tried to do this in Golang, you would know that’s it isn’t all that simple at first.

The easiest way to convert between String and Integers in Golang is as follows:

String to Integer

My go-to option to resolve this problem would be with the strconv module.

your_str := "443"
your_int := strconv.Atoi(your_str)

Integer to String

Just as we used the strconv before, we can also do this in reverse as follows:

your_int := 443
your_str := strconv.Itoa(your_int)

Other ways to do this

There are actually 3 ways to do this, even though we used the strconv.Itoa method above.

strconv.Atoi(...)is very fast and implemented like this:

x, err := strconv.Atoi(numstr)

strconv.ParseInt(...) is also very fast and implemented like this:

x, err := strconv.ParseInt(numstr, 10, 64)

fmt.Sscanf(...) is a bit slower but most flexible generally and implemented like this:

n, err := fmt.Sscanf(numstr, "%d", &x)