Home > Back-end >  How do you append function result, while overwriting error?
How do you append function result, while overwriting error?

Time:11-11

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() // ?

CodePudding user response:

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

  • Related