'Defer to outside a function

A common pattern I use is:

resource.open()
defer resource.close()

sometimes checking errors in between, which leads to:

err := resource.open()
if err != nil{
     //do error stuff and return
}
defer resource.close()

Sometimes I will need multiple open/close resources in a row, leading to a variation of the previous 5 lines to be repeated one after another. This variation may be repeated verbatim several times in my code (where I need all the same resources).

It would be wonderful to wrap all this in a function. However doing so would close the resource as soon as the function call is over. Is there any way around this - either deferring to a "level up" the call stack or some other way?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source