How to Convert Golang string to int
December 6, 2020

Converting between numbers and strings is a very common task in many programs.
In this short tutorial, you’ll understand:

  • How to convert a Golang string to int
  • How to convert a Golang int to string

string to int

To convert a string to integer in Go you use Atoi function from the standard library.

Example:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	s := "10"
	if i, err := strconv.Atoi(s); err == nil {
		fmt.Printf("%T, %v", i, i)
	}

}

Output:

int, 10

int to string

To convert an integer to string in Go you use Itoa function from the standard library.

Example:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	i := 10
	s := strconv.Itoa(i)
	fmt.Printf("%T, %v\n", s, s)

}

Output:

string, 10