How to convert a string to an integer using strconv.Atoi() in Golang?

To convert a string to an integer using strconv.Atoi() in Golang, follow these steps:

  1. Import the strconv package:
import "strconv"
  1. Call the 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")
  1. Check if the conversion was successful by checking the error. If the conversion fails, an error will be returned. Handle the error appropriately:
if err != nil { fmt.Println("Conversion error:", err) return }
  1. Use the converted integer 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.