Last updated on December 7, 2022
In golang, we can convert a string value into an integer. To do that we will need to import a few packages listed below.
The fmt package has Println() that helps to print the variable’s value.
Reflect package provides ValueOf() and Kind() functions that chain together and return the variable’s data type.
The strconv package has Atoi() function that accepts the string value as an argument and converts it into an integer.
To begin with, let’s create and import all the required packages.
import("fmt"
"reflect"
"strconv"
)
After importing all the packages, we will be keeping all the code inside the main function. So create a variable and assign it to the string value.
var cups string = "5"
fmt.Println(cups)
// Output: 5
Next, let’s check the data type of cups variable, to do that we can use ValueOf() and Kind() functions from reflect package that helps to show the data type.
// check data type of variable
fmt.Println(reflect.ValueOf(cups).Kind())
// Output: string
In the next step, let’s convert the cups value data type into an integer. To convert the cups value data type into an integer, we can use Atoi() function from the strconv package.
// convert string into integer
convertIntoInteger, err := strconv.Atoi(cups)
if err != nil{
fmt.Println("Failed to convert or any other error")
}
Here, we have two inferred variables that will store the value of the Atoi() function. In case, all goes well then Atoi() function returns the converted value that will be assigned to convertIntoInteger variable.
Now, to make sure that the data type is converted we can check it through ValueOf() and Kind() functions.
fmt.Println(reflect.ValueOf(convertIntoInteger).Kind())
// Output: int
Below is the complete code.
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
var cups string = "5"
fmt.Println(cups)
// Output: 5
// check data type of variable
fmt.Println(reflect.ValueOf(cups).Kind())
// Output: string
// convert string into integer
convertIntoInteger, err := strconv.Atoi(cups)
if err != nil{
fmt.Println("Failed to convert or any other error")
}
// check data type of variable
fmt.Println(reflect.ValueOf(convertIntoInteger).Kind())
// Output: int
}
To convert a string value into an integer, you need Atoi() function from strconv package. It takes the value as an argument and converts it into an integer.