Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically set a variable in a defer call

Tags:

go

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.

like image 387
samol Avatar asked Dec 25 '22 05:12

samol


1 Answers

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")
}
like image 124
Sean Avatar answered Jan 05 '23 07:01

Sean