0

Usually, result, err := func() is used.

When one of the variables is already initialized:

_, err := func()

var result string
result, err = func()

Doing:

result, err = func()
all_results += result // seems redundant and unneeded

How do you append results to one of them (result), and reset the other one?

// along the lines of this:
var result slice
// for loop {
result, _ += func() // combine this line
_, err = func() // with this line

Can you do:

result +=, err = func()
// or
result, err +=, = func()
// or
result, err += = func()
// or
result, err (+=, =) func() // ?
u15p7fgy863eiq5
  • 205
  • 2
  • 5

1 Answers1

2

The language spec does not support different treatment for multiple return values.

However, it's very easy to do it with a helper function:

func foo() (int, error) {
    return 1, nil
}

func main() {
    var all int

    add := func(result int, err error) error {
        all += result
        return err
    }

    if err := add(foo()); err != nil {
        panic(err)
    }
    if err := add(foo()); err != nil {
        panic(err)
    }
    if err := add(foo()); err != nil {
        panic(err)
    }
    fmt.Println(all)
}

This will output 3 (try it on the Go Playground).

If you can move the error handling into the helper function, it can also look like this:

var all int

check := func(result int, err error) int {
    if err != nil {
        panic(err)
    }
    return result
}

all += check(foo())
all += check(foo())
all += check(foo())

fmt.Println(all)

This outputs the same, try this one on the Go Playground.

Another variant can be to do everything in the helper function:

var all int

handle := func(result int, err error) {
    if err != nil {
        panic(err)
    }
    all += result
}

handle(foo())
handle(foo())
handle(foo())

fmt.Println(all)

Try this one on the Go Playground.

See related: Multiple values in single-value context

icza
  • 389,944
  • 63
  • 907
  • 827
  • Could you gather the errors instead / as well; and handle them at once (one `if != nil`, outside of a `for`)? – u15p7fgy863eiq5 Nov 07 '21 at 18:13
  • @u15p7fgy863eiq5 You can of course do anything. One option is to store the error in a variable, which is checked by the helper function. If there was a previous error, the helper function can be a no-op. – icza Nov 07 '21 at 18:17
  • would you think multi-operator short variable definitions would be useful enough as a feature to propose to golang? – u15p7fgy863eiq5 Nov 07 '21 at 18:32
  • 2
    @u15p7fgy863eiq5 I don't think it's needed, but that's just my opinion. – icza Nov 07 '21 at 18:50