0

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.

Gabe
  • 5,643
  • 3
  • 26
  • 54
  • 1
    See possible duplicate [Multiple values in single-value context](https://stackoverflow.com/questions/28227095/multiple-values-in-single-value-context/28233172#28233172). – icza Aug 21 '19 at 13:55
  • @icza That question was simply asking how to convert string to an int. I already knew how to do that, what I wanted was to do it in an if statement and throw away the error. – Gabe Aug 21 '19 at 14:10
  • On the general principle that errors you are sure won't happen, actually will happen, I'd use a `mustXXX` wrapper function that panics if the error that cannot happen, does happen. – torek Aug 21 '19 at 20:20

2 Answers2

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

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
peterSO
  • 158,998
  • 31
  • 281
  • 276