In Go, you can use the Atoi
function in the strconv
package to convert a numeric string to an integer.
Note: This function returns an int in base 10. It is equivalent to
ParseInt(s, 10, 0)
.
func Atoi(s string) (int, error)
Atoi
takes a valid numeric string as a parameter.
If the conversion succeeds, the function will return a nil
error and the int
we are searching for; otherwise, it will return an error
.
package mainimport ("fmt""strconv")func main() {// in this case, we want to convert// the string '10' to the int 10s, err := strconv.Atoi("10");if err != nil {fmt.Println("Can't convert this to an int!")} else {fmt.Println(s)}// we can also convert negative numberss1, err1 := strconv.Atoi("-2");if err1 != nil {fmt.Println("Can't convert this to an int!")} else {fmt.Println(s1)}// now, we will try to convert a not valid// string and handle the errors2, err2 := strconv.Atoi("Hello educative!");if err2 != nil {fmt.Println("Can't convert this to an int!")}else{fmt.Println(s2)}}