Golang cannot convert (type string) to type int

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)
Code language: Go (go)

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)
Code language: Go (go)

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)
Code language: Go (go)

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

x, err := strconv.ParseInt(numstr, 10, 64)
Code language: Go (go)

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

n, err := fmt.Sscanf(numstr, "%d", &x)
Code language: Go (go)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments