将字符串的错误值丢掉进行int转换

I have a Go program that I simply want to convert a string to an int. I understand the function:

val, err := strconv.Atoi(myValueAsAString)

works and I can check the error by the following:

if err != nil {
    //handle error
}

But what if I am 100% the string will be a number, and I want to convert it to an int in an if statement, like the following:

if 45 + strconv.Atoi(value) >= 90 {
    //do something
}

But strconv.Atoi also returns an error value as well, so how can I throw that away and essentially do what I did above, without having to define the variable above the if statement and use it in the if statement. I'm not sure if this is possible or not, but I would love to know.

  1. Create a wrapper function that discards the error result:
func atoi(s string) int {
    value, _ := strconv.Atoi(s)
    return value
}
if 45 + atoi(value) >= 90 {
    //do something
}
  1. Or, do the conversion as a statement before the if and ignore the error result:
if i, _ := strconv.Atoi(value); 45 + i >= 90 {
    // do something
}

I simply want to convert a string to an int.

What if I am 100% the string will be a number.

I want to convert a string of numeric digits to an int in an if statement, like the following:

if 45 + strconv.Atoi(value) >= 90 {
    //do something
}

What if you are wrong?


Write a simple Go wrapper function for strconv.Atoi. In Go, don't ignore errors.

// ASCII digits to integer.
func dtoi(s string) int {
    i, err := strconv.Atoi(s)
    if err != nil {
        panic(err)
    }
    return i
}

For example,

package main

import (
    "fmt"
    "strconv"
)

// ASCII digits to integer.
func dtoi(s string) int {
    i, err := strconv.Atoi(s)
    if err != nil {
        panic(err)
    }
    return i
}

func main() {
    value := "1024"
    if 45+dtoi(value) >= 90 {
        fmt.Println("do something")
    }
}

Playground: https://play.golang.org/p/I3plKW2TGSZ

Output:

do something