HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

Convert string to integer type in Go?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringconverttypeinteger

Problem

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

Code Snippets

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

Context

Stack Overflow Q#4278430, score: 661

Revisions (0)

No revisions yet.