Quantcast
Channel: Defer to outside a function - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Defer to outside a function

$
0
0

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?


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>