Search code examples
stringgotype-conversion

Convert string to integer type in Go?


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?


Solution

  • For example strconv.Atoi.

    Code:

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        s := "123"
    
        // string to int
        i, err := strconv.Atoi(s)
        if err != nil {
            // ... handle error
            panic(err)
        }
    
        fmt.Println(s, i)
    }