how to assign only on return value of a function to field of an struct in golang?

3.4k Views Asked by At

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

1

There are 1 best solutions below

0
On

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