How to convert a string to an integer in Golang?

To convert a string to an integer in Golang, you can use the strconv package. Here's an example:

package main import ( "fmt" "strconv" ) func main() { str := "42" num, err := strconv.Atoi(str) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Number:", num) }

In this example, we use the strconv.Atoi() function to convert the string str to an integer. The function returns two values: the converted integer and an error if any. If the conversion is successful, strconv.Atoi() returns the integer value and err will be nil. Otherwise, it returns an error.

Note that strconv.Atoi() only works with strings representing integer values. If the string cannot be converted to an integer, it will return an error.