Rain
Rain

Reputation: 47

Is it possible to get a single value from a function (which has multiple return values) during a statement?

Lets say for example add(int, int) returns and int and an error, and I want to append the int return value into a string. The way I know how to do it in go is:

foo := ""
bar, _ := add(1, 2)
foo += strconv.Itoa(bar)

However, if add() didn't return an error variable, I can just do foo += strconv.Itoa(add(1, 2)).

Is it possible to ignore the error variable during the statement to do something like that?

Upvotes: 2

Views: 1288

Answers (2)

Hymns For Disco
Hymns For Disco

Reputation: 8395

Disclaimer (my opinion): This answer is just for fun. I don't recommend ever using this. Ignoring errors is bad, and trying to compactify every line of code is a fool's errand. This just illustrates some interesting concepts about how Go handles multiple return values, and I learned something new while writing this, so I thought I'd share.

Related: The more practical cousin of this problem is the "Must pattern", used by some of the standard library including templates. It involves taking a value and an error, panicing if the error is not nil, and then returning the value. See this (currently frozen) proposal

You need a wrapper function to do this. The multiple return values will automatically expand to fill the arguments.

See this example which matches the types of add()

func ignoreError(i int, err error) int {
    return i
}

Calling:

foo := ""
foo += strconv.Itoa(ignoreError(add(1, 2)))

Here's a more general alternative, which will take any number of values from another function and return the first.

func takeFirstValue(v ...interface{}) interface{} {
    if len(v) == 0 {
        return nil
    }
    return v[0]
}

Calling:

    foo := ""
    foo += strconv.Itoa(takeFirstValue(add(1, 2)).(int))

This option requires casting at the call site .(int) to restore the data type, as takeFirstValue returns interface{}.

Upvotes: 3

Volker
Volker

Reputation: 42432

Is it possible to ignore the error variable during the statement to do something like that?

No, Go offers no language construct for something like this.

(But you can have your own Must... functions like you'll find in package regexp or text/template.)

Upvotes: 1

Related Questions