1

let's say we have a struct like this:

type Data struct {
  a int
}

and we want to get a single return value of a function that returns multiple values and assign it to an object of Data, for example

data := Data {
  a: strconv.Atoi("1000")
}

the code above does not work because Atoi returns two value, a number and an error, so we need to handle the extra value (error) somehow, but in my case, I do not need to evaluate error value and it is not possible to dismiss it using _ keyword.

how can I achieve this when initializing a struct, I want to get rid of the error return value

sepisoad
  • 2,201
  • 5
  • 26
  • 37

1 Answers1

5

There is no generic way to get just one of returned parameters (Maybe you could implement something with reflect package that returns interface{}).

Other than that it's not good to ignore errors. If you are sure that there's no error implement a helper function like this:

func myAtoi(s string) int {
    i, err := strconv.Atoi(s)
    if err != nil {
        panic(err)
    }
    return i
}

data := Data {
    a: myAtoi("1000")
}
Arman Ordookhani
  • 6,031
  • 28
  • 41