a shot of dev knowledge

RELATED TAGS

How to convert a string to an int in Go

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).

Visual rappresentation of Atoi function

Syntax

func Atoi(s string) (int, error)

Parameters

Atoi takes a valid numeric string as a parameter.

Return value

If the conversion succeeds, the function will return a nil error and the int we are searching for; otherwise, it will return an error.

Example

package main

import (
	"fmt"
	"strconv"
)

func main() {

	// in this case, we want to convert 
	// the string '10' to the int 10
	s, 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 numbers
	s1, 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 error
	s2, err2 := strconv.Atoi("Hello educative!");
	if err2 != nil {
		fmt.Println("Can't convert this to an int!")
	}else{
		fmt.Println(s2)
  	}
}

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring