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:
- An integer if conversion is successful.
- An error if any error is thrown.
Coding example
In the example below, we convert a string into an integer.
package main//import packagesimport("fmt""strconv")//program execution starts herefunc main(){//declare a stringstr := "34"fmt.Println(str + "2")//convert string to intn , err := strconv.Atoi(str)//check if error occuredif err != nil{//executes if there is any errorfmt.Println(err)}else{//executes if there is NO errorfmt.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
strthen print it. -
In line 16, we convert the string
strtointusing theAtoi()function, and we assign the two returned values to variablesnanderr. -
In lines 19-26, we check if any error occurred.
- If an error occurs,
erris printed in line 22. - If no error occurs, an integer value (original value + 2) is printed on line 26.
- If an error occurs,