Golang atoi: How to Use Atoi() Function in Go

Golang provides a built-in package called strconv for conversions like string to int and int to string. Parse methods would return an error if they received invalid input.

Golang Atoi

Golang Atoi() is a built-in function that comes with a strconv package used to convert a given string in the given base (10) and bit size (0) into an integer value. The strconv.Atoi() function takes an integer as an argument and returns the string representation of the input value.

To convert string value to integer value, use Atoi() function.

Syntax

func Atoi(s string) (int, error)

Arguments

The Atoi() method takes a string as an argument.

Return value

It either returns an integer or an error if the value is not compatible with converting it into an integer.

Example

To use the Atoi() function in Golang, you need to import the strconv package into your program. In addition, the fmt package is valid when you need to execute I/O operations like printing on the console.

package main

import (
 "fmt"
 "strconv"
)

func main() {
   dataString := "19"
   fmt.Printf("%v \n", dataString)
   fmt.Printf("%T \n", dataString)
   fmt.Println("After using Atoi() Function")
   if s, err := strconv.Atoi(dataString); err == nil {
   fmt.Printf("%v \n", s)
   fmt.Printf("%T \n", s)
 }
}

Output

19
string

After using Atoi() Function

19
int

In this example, we imported two packages.

  1. fmt
  2. strconv

Inside the main() function, we declare a variable with a string value and then print its value and data type.

Using the if statement, we convert a string to an integer using strconv.Atoi() function.

The Atoi() function is equivalent to ParseInt() function which is also useful to convert to type int.

Example 2

package main

import (
 "fmt"
 "strconv"
)

func main() {
   fmt.Println(strconv.Atoi("19"))
   fmt.Println(strconv.Atoi("-19"))
   fmt.Println(strconv.Atoi("212121"))
   fmt.Println(strconv.Atoi("-2119"))
   
   fmt.Println(strconv.Atoi("ff"))
   fmt.Println(strconv.Atoi("123abc"))
}

Output

19 <nil>
-19 <nil>
212121 <nil>
-2119 <nil>
0 strconv.Atoi: parsing "ff": invalid syntax
0 strconv.Atoi: parsing "123abc": invalid syntax

We took every possible string type in this example and converted it into an integer.

The strconv.Atoi() function also returns an error. The error object will be nil if there is no error.

In this example, if there is no error, nil is returned. Otherwise, an error is returned. For example, while parsing, if it finds a string that can not be converted into an integer, it returns an invalid syntax error.

The Atoi() function is a convenient method for base-10 int parsing.

That’s it for this tutorial.

Related Posts

Golang Itoa()

Golang FormatInt()

Leave a Comment