Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Converting string to integer - strconv, Atoi

  • strconv
  • Atoi
  • err
  • nil
package main

import (
	"fmt"
	"strconv"
)

func main() {
	var i int
	i, _ = strconv.Atoi("42")
	fmt.Printf("%v %T\n", i, i) // 42 int

	i, _ = strconv.Atoi("0")
	fmt.Printf("%v %T\n", i, i) // 0 int

	i, _ = strconv.Atoi("23\n")
	fmt.Printf("%v %T\n", i, i) // 0 int

	i, _ = strconv.Atoi("17x")
	fmt.Printf("%v %T\n", i, i) // 0 int
}
42 int
0 int
0 int
0 int
  • In the first two examples the conversion was successful.
  • In the 3rd and 4th examples it failed.
  • How can we know?

While internally Go can represent numbers, the communication with the outside world is always using strings. So when we read from a file we always get strings. When we ask the user to type in a number and the user types in a number, we still receive it as a string. For example as the string "42". So we need a way to convert a string that looks like a number to the numeric representation of Go.