Your assignments in the deferred function are to the local
variable `err`, not the return value of `Execute` -- you can't
change the return value in the deferred function unless it
has a name.
You want to write
func Execute() (err error) {
defer func() {
...
Now the return value is named and can be updated in the
body of the deferred function.
On 11 October 2016 at 11:16, Henry <[email protected]> wrote:
> Hi,
>
> I stumbled upon this problem earlier and I wonder whether this is actually
> the intended behavior of defer or a bug.
>
> Here is the code to illustrate the problem (or you can view it in the Go
> playground at https://play.golang.org/p/s2hdAmirrl ).
>
> package main
>
> import (
> "errors"
> "fmt"
> )
>
> func main() {
> err := Execute()
>
> //err is nil. I thought it is supposed to return the commit error?
> fmt.Printf("%v", err)
> }
>
> func Execute() error {
> var err error
> defer func() {
> if err == nil {
> err = Commit()
> }
> if err != nil {
> Rollback()
> }
> }()
>
> err = Process()
> return err
> }
>
> func Process() error {
> return nil
> }
>
> func Commit() error {
> return errors.New("Mocked commit error")
> }
>
> func Rollback() {
> }
>
> It appears to me that defer works with the local copy of the variable,
> instead of a direct reference. I think as a rule I mustn't make any variable
> assignment in defer. I wonder whether this is by design.
>
> Thanks.
>
> Henry
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
--
Chris "allusive" Dollin
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.