How to convert a string to int in Golang

A string can be converted into an int data type using the Atoi function provided by the package strconv.

The package strconv supports conversions to and from strings to other data types.

Syntax

strconv.Atoi(str)

Parameters

str: It contains the string value we want to convert to an int.

Return value

This function returns two values:

  1. An integer if conversion is successful.
  2. An error if any error is thrown.

Coding example

In the example below, we convert a string into an integer.

package main
//import packages
import(
"fmt"
"strconv"
)
//program execution starts here
func main(){
//declare a string
str := "34"
fmt.Println(str + "2")
//convert string to int
n , err := strconv.Atoi(str)
//check if error occured
if err != nil{
//executes if there is any error
fmt.Println(err)
}else{
//executes if there is NO error
fmt.Println(n + 2)
}
}

Explanation

In the code above:

  • In line 5, we import the format package fmt, which is used to format the input and output.

  • In line 6, we import the string conversion package strconv, which is used to convert the string to other datatypes.

  • In line 10, program execution starts from the main() function in Golang.

  • In line 13, we declare a string str, which we want to convert into an integer.

  • In line 14, we concatenate “2” in str then print it.

  • In line 16, we convert the string str to int using the Atoi() function, and we assign the two returned values to variables n and err.

  • In lines 19-26, we check if any error occurred.

    • If an error occurs, err is printed in line 22.
    • If no error occurs, an integer value (original value + 2) is printed on line 26.

Free Resources