golang

Golang String to Int

Golang or Go is a free, simplistic, modern, and open-source programming language. It is a high-level language and provides versatile features and data types for modern development.

One data type provided natively by the Go programming language is a String. A string allows you to store a sequence of characters, including alphanumerical characters.

In some cases, you may have a numerical value stored in a string format. To perform any operations involving an int type, you must convert it to an int.

This tutorial will assist you in discovering various methods and techniques of converting a string to an int in Go.

Golang Create String

In Go, we use double quotation marks to represent a string. An example program is shown below:

package main

import “fmt

func main() {
    var value = “1000
    fmt.Println(value)
}

We have a string variable holding a ‘numerical’ value in the example program. Keep in mind that the value may appear numerical to us but the value is a string to the compiler.

Hence, if a mathematical operation on the value is attempted, the compiler will return an error.

Package main

import “fmt

func main() {
    var value = “1000
    fmt.Println(value * 3)
}

The compiler’s output will be:

$ go run string_to_int.go
# command-line-arguments
.\string_to_int.go:7:14: invalid operation: value * 3 (mismatched types string and untyped int)

Golang Parse String to Int #1

Go provides the Atoi() function from the strconv package to parse a string to an Int type.

https://pkg.go.dev/strconv#Atoi

For example, to convert the variable ‘value’ from the previous program to an int:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    value := "1000"
    if n, err := strconv.Atoi(value); err == nil {
        fmt.Println(n * 3)
    }
}

From the program above, we start by importing the strconv package. This gives us access to the Atoi() function. We then use the Atoi() function to parse the string to an int and perform a mathematical operation.

We can check the type of the value as:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    value := "1000"
    if n, err := strconv.Atoi(value); err == nil {
        fmt.Printf("%T \n", n)
        fmt.Println(n * 3)
    }
}

The program results in output as:

$ go run string_to_int.go
int
3000

Although we use the Atoi() function to convert a string to an int, we must ensure that the value can be converted to an int.

If we attempt to convert a string such as a name to an int, the function will raise an error.

Take, for example, the program below:

package main

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

func main() {
    value := "linuxhint"
    n, err := strconv.Atoi(value)
    log.Fatal(err)
    fmt.Println(n)
}

In the code above, we are attempting to convert the string “linuxhint” to a string that is an unsupported format.

The code above should raise an error as:

$ go run string_to_int.go
2022/05/31 02:15:22 strconv.Atoi: parsing "linuxhint": invalid syntax
exit status 1

Golang Parse String to Int #2

In the strconv package, we have access to the ParseInt function which allows us to parse a string to a given base (0, 2 to 36).

https://pkg.go.dev/strconv#ParseInt

Let us take an example as shown below:

 package main

import (
    "fmt"
    "strconv"
)

func main() {
    value := "1000"
    if n, err := strconv.ParseInt(value, 10, 64); err == nil {
        fmt.Printf("%T: %v\n", n, n)

    }
}

Pay attention the ParseInt() function. We pass three main arguments in it: the first is the value we wish to parse to an int and the second represents the base. The base is a value ranging from 0, or 2 to 36.

The final argument is the bit size which specifies the integer type the resulting value fits. Accepted values include 0, 8, 16, 32, and 64, conforming to int, int8, int16, int32, and int64.

Final Thoughts

You learned how to convert a string to an int type in Go through this tutorial.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list