Search code examples
goresultsetexit-code

Can we write loops/conditions/block of code in a defer?


Hi I am new to golang,

I use defer to close my result set like this.

defer res.Close() 

I would like to check whether res is nil or not before calling res.Close().

I have below code block in the end of the function but it is not invoked when exited due to some error.

if(res!=nil){
            res.Close()
        }

I would like to know is there any way I could achieve this using defer .

defer  if(res!=nil){
                res.Close()
            }

Also what is the Idiomatic way for handling these situations?


Solution

  • You can pass to defer a function call, and this can be a function literal :

    defer func() {
         if res!=nil {
              res.Close()
         }
    }()
    

    Note that you usually avoid this problem by writing the defer statement right after the resource assignment.