Is it possible to put defer
in sub function?
I.e., for line 12~16 of func test1()
in
https://play.golang.org/p/evabhcjvNs (enclosed below)
Is there any possibility to put them in sub function?
Like what I tried in test2()
(but that behavior is different than test1()
).
The reason I'm asking is that, for line 12~16 of func test1()
, my actual code is to restore the variable from persistent data, then use defer
to save it when test1()
is done. However, there are cases that the whole restore/save is not necessary, so I'm thinking a better way to control it.
thanks
package main
import "log"
func main() {
test1()
log.Printf("====
")
test2()
}
func test1() {
r, err := Open("a")
if err != nil {
log.Fatalf("error opening 'a'
")
}
defer r.Close()
r.Use()
}
func test2() {
r := subc()
r.Use()
}
func subc() *Resource {
r, err := Open("a")
if err != nil {
log.Fatalf("error opening 'a'
")
}
defer r.Close()
return r
}
type Resource struct {
name string
}
func Open(name string) (*Resource, error) {
log.Printf("opening %s
", name)
return &Resource{name}, nil
}
func (r *Resource) Use() error {
log.Printf("using %s
", r.name)
return nil
}
func (r *Resource) Close() error {
log.Printf("closing %s
", r.name)
return nil
}