|
|
|
|
|
by Groxx
3103 days ago
|
|
Both seem like fair options to me. With function scope, you can func f() {
x := ...
if x.something() {
x.doSomethingEarlier()
defer x.cleanup()
}
// use x however you like
}
where scope-based forces you to do stuff like func f() {
x := ...
if x.something() {
x.doSomethingEarlier()
defer x.cleanup()
// use x however you like
} else {
// use x however you like
}
}
In a scope-based defer, you'd have to keep all related code in the scope, nesting it another layer deeper / possibly duplicating it.On the flip-side is of course that this doesn't work like most would probably want in function-scoped: for i := 0; i < 4; i++ {
x := get(i)
defer x.cleanup()
x.whatever()
}
and you're forced to for i := 0; i < 4; i++ {
x := get(i)
func() {
defer x.cleanup()
x.whatever()
}()
}
I've seen both of these patterns pretty frequently, in Go and in other languages. Go could, of course, have both a func_defer and a scope_defer, but that doesn't seem like it'd fit with the fairly strong focus on keeping the language feeling small and simple. So they had to pick one, and it can't handle both cases. |
|