5

Example code:

package main

import (
    "errors"
    "fmt"
)

func main() {
    err := errors.New("error 1")
    defer fmt.Println(err)

    err = errors.New("error 2")
}

In this case, I want fmt.Println to print out error 2.

samol
  • 18,950
  • 32
  • 88
  • 127
  • Looks like that's not the way to go about it, according to [this blog post](https://blog.golang.org/defer-panic-and-recover) - arguments are always computed when it encounters the `defer` statement. Still thinking if there's a different way to achieve what you want. – dwanderson May 18 '16 at 16:43
  • Possible duplicate of [Defer usage clarification](http://stackoverflow.com/questions/31404471/defer-usage-clarification) – icza May 18 '16 at 16:55

1 Answers1

11

err is already defined when you set the defer so what you what you likely want to do is wrap it in a func like below. Hope this helps.

package main

import (
    "errors"
    "fmt"
)

func main() {
    err := errors.New("error 1")

    defer func() {
      fmt.Println(err)
    }()

    err = errors.New("error 2")
}
Sean
  • 1,048
  • 1
  • 11
  • 23
  • What happens if the last line where `errors.New("error 2")` is assigned to `err` is never reached i.e. a panic occurs beforehand and triggers the deferred function before it? – Pandemonium May 18 '16 at 19:12
  • 1
    It would print "error 1" because that's the last value given before "error 2". The defer func is pulling the value for err from the scope of main, so it will use the last value assigned. – Sean May 18 '16 at 20:07
  • Exactly, that's why I asked. In such case, should the intended error value be injected into the deferred function then? – Pandemonium May 18 '16 at 23:32
  • That depends on what you're trying to accomplish. If you assign the err to the defer func at the point it's declared then it's going to use it's current value see here https://play.golang.org/p/CpOpobmlyp. So you'd be back to square one in the original question. – Sean May 18 '16 at 23:37