Converting string to integer - strconv, Atoi



examples/convert-string-to-integer/convert_string_to_integer.go
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

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.