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

Answer by Burak Serdar for Defer to outside a function

$
0
0

One way to do this is using an "initializer" function with callback:

func WithResources(f func(Resource1, Resource2)) {   r1:=NewResource1()   defer r1.Close()   r2:=NewResource2()   defer r2.Close()   f(r1,r2)}func F() {  WithResources(func(r1 Resource1, r2 Resource2) {    // Use r1, r2  })}

The signature of the function f depends on your exact use case.

Another way is to use a struct for a resource set:

type Resources struct {   R1 Resource1   R2 Resource2   ...}func NewResources() *Resources {   r:=&Resources{}   r.R1=NewR1()   r.R2=NewR2()   return r}func (r *Resources) Close() {   r.R1.Close()   r.R2.Close()}func f() {   r:=NewResources()   defer r.Close()   ...}

Viewing all articles
Browse latest Browse all 3

Trending Articles



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