1. 程式人生 > >5 Gotchas of Defer in Go (Golang) — Part II

5 Gotchas of Defer in Go (Golang) — Part II

#5 — Point of no return?

Returning values from a deferred func practically has no effect on the caller. However, you can still use named result values to change the result values.

Example

func release() error {
defer func() error {
return errors.New("error")
}()
  return nil
}

Output

nil

Solution

Defer can change the named result values.

func release() (err error) {
defer func() {
err = errors.New("error")
}()
  return nil
}

Output

"error"

Why it works?

Here, we’re assigning a new value to release func’s err result value inside the defer. And, the func returns that value. The defer doesn’t directly return a value here, it helps returning the value.

Tip

You don’t need to use defer everywhere. You can also just return the error directly without defer.

Defers are more handy when there are multiple return paths and you want to catch them all in a single place. Better to think more about how you can simplify your code further.