Go – Convert string to integer type in Go

gostringtype conversion

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?

Best Answer

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)
}