Convert string to integer type in Go?

Matt Joiner picture Matt Joiner · Nov 25, 2010 · Viewed 225.5k times · Source

I'm trying to convert a string returned from flag.Arg(n) to an int. What is the idiomatic way to do this in Go?

Answer

peterSO picture peterSO · Nov 25, 2010

For example,

package main

import (
    "flag"
    "fmt"
    "os"
    "strconv"
)

func main() {
    flag.Parse()
    s := flag.Arg(0)
    // string to int
    i, err := strconv.Atoi(s)
    if err != nil {
        // handle error
        fmt.Println(err)
        os.Exit(2)
    }
    fmt.Println(s, i)
}