To convert a string to an integer using strconv.Atoi()
in Golang, follow these steps:
strconv
package:import "strconv"
Atoi()
function from the strconv
package, passing the string as a parameter. This function returns an integer and an error:number, err := strconv.Atoi("1234")
if err != nil {
fmt.Println("Conversion error:", err)
return
}
number
in your code:fmt.Println("Converted number:", number)
Here's the complete example:
package main
import (
"fmt"
"strconv"
)
func main() {
// Convert a string to an integer
number, err := strconv.Atoi("1234")
if err != nil {
fmt.Println("Conversion error:", err)
return
}
fmt.Println("Converted number:", number)
}
Output:
Converted number: 1234
Note: If the string cannot be converted to an integer, the Atoi()
function will return an error. Make sure to handle the error appropriately to avoid unexpected behavior in your code.