Golang cannot convert (type string) to type int

0 min read 174 words

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)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags