How to Convert Golang String to Int

An int and string are basic data types in Golang. Go int has a platform-dependent size, as, on a 32-bit system, it holds a 32-bit signed integer int32, while on a 64-bit system, it holds a 64-bit signed integer which is int64.

To define an integer in Golang,

var data int

To declare a string in Golang,

var strdata := "Marilyn Blonde Monroe"

Let’s see how to convert a string data type to an integer data type in Go.

Golang string to int

To convert a string to int in Golang, use the strconv.Atoi() function. The strconv.Atoi() is a built-in Go function that is used to convert string data type into an integer.

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

In this example, we imported two packages.

  1. fmt
  2. strconv

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.

Inside the main() function, we declared a string and to convert that string into an integer, used the strconv.Atoi() function.

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

To print the data type of a variable in Golang, use the printf(“%T”) function.

You can see that it atoi() function returns an integer and we verified this using the printf(“%T”) function.

Converting string to int using ParseInt() function

To convert a string that can contain digit characters into an integer in Go, use the strconv.ParseInt() function. The ParseInt() is a built-in Gol function that interprets a string in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value.

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 which is 10,  a bit size which is 1, and returns an integer value.

That’s it.

Related posts

Golang int to string

Golang string to json

Golang string to byte array

Leave a Comment