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

You can use the strconv.Atoi() function to convert the string data type into an integer in Go.

Syntax

func Atoi(str string) (int, error)

Parameters

The str 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

The fmt package in Go implements formatted I/O with functions analogous to C language’s printf() and scanf() functions.

The strconv package implements conversions to and from string representations of basic data types.

If it returns an error, we print it; otherwise, we will print the output with its data type.

Method 2: Using the fmt.ParseInt() function

To convert a string containing digit characters into an integer in Go, you can use the “strconv.ParseInt()” function. The ParseInt() is a built-in function that 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.

Leave a Comment