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.
strconv.Atoi(str)
str
: It contains the string
value we want to convert to an int
.
This function returns two values:
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)}}
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.
err
is printed in line 22.