How to Convert String to Int in Golang

To convert a string to int in Golang, you can use the “strconv.Atoi()”, “strconv.ParseInt()”, or “fmt.Sscan()” function.

Method 1: Using the strconv.Atoi() function

The strconv.Atoi() function accepts a string as its argument and returns an “int” type value.

Syntax

func Atoi(str string) (int, error)

Parameters

str: It is a string.

Example

package main

import (
  "fmt"
  "strconv"
)

func main() {
  str := "1921"
  op, err := strconv.Atoi(str)
  if err != nil {
    panic(err)
  }
  fmt.Printf("%T \n%v \n", op, op)
}

Output

int
1921

Method 2: Using the fmt.ParseInt() function

The ParseInt() function interprets a string in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value.

Syntax

func ParseInt(str string, base int, bitSize int) (i int64, err error)

Parameters

  1. str: The string value to be converted into an integer number.
  2. base: The base value of the given value. It can range from 0, 2, to 36.
  3. bitSize: It specifies the integer type, such as int(0), int8(8), int16(16), int32(32), and int64(64).

Example

package main

import (
  "fmt"
  "strconv"
)

func main() {
  str := "1921"
  op, err := strconv.ParseInt(str, 10, 0)
  if err != nil {    
     panic(err)
  }
  fmt.Printf("%T \n%v \n", op, op)
}

Output

int64
1921

And we get an integer converted from a string. The ParseInt() function takes a string, a base of 10,  a bit size of 1, and returns an integer value.

Method 3: Using the fmt.Sscan() function

The fmt.Sscan() function scans string arguments and stores them into variables. It reads the string with spaces and assigns it to consecutive Integer variables.

Syntax

func Sscan(str string, a ...interface{}) (n int, err error)

Parameters

  1. str string: This parameter contains the specified text that will be scanned.
  2. a …interface{}: This parameter receives each text.

Example

package main

import (
  "fmt"
  "reflect"
)

func main() {
  str_val := "19"
  int_val := 21
  _, err := fmt.Sscan(str_val, &int_val)
  fmt.Println(int_val, err, reflect.TypeOf(int_val))
}

Output

19 <nil> int

That’s it.