| ▲ | tgv 4 days ago |
| Currently, you can write if (some condition) { defer x() }
When it's lexically scoped, you'd need to add some variable. Not that that happens a lot, but a lexically scoped defer isnt needed often either. |
|
| ▲ | iainmerrick 3 days ago | parent | next [-] |
| What's an example of where you'd need to do that? I can't recall ever needing that (but that might just be because I'm used to lexical scoping for defer-type constructs / RAII). |
| |
| ▲ | tgv 3 days ago | parent [-] | | Someone already replied, but in general when you conditionally acquire a resource, but continue on failing. E.g., if you manage to acquire it, defer the Close() call, otherwise try to get another resource. Another example I found in my code is a conditional lock. The code runs through a list of objects it might have to update (note: it is only called in one thread). As an optimization, it doesn't acquire a lock on the list until it finds an object that has to be changed. That allows other threads to use/lock that list in the meantime instead of waiting until the list scan has finished. I now realize I could have used an RWLock... |
|
|
| ▲ | atombender 3 days ago | parent | prev | next [-] |
| I frequently use that pattern. For example, something like this: a := Start()
if thingEnabled {
thing := connectToThing()
defer thing.Close()
a.SetThing(thing)
}
a.Run(ctx)
|
|
| ▲ | raluk 3 days ago | parent | prev [-] |
| Having lexicial scope it is same as -> defer fn{if(some condition) x() }() within scope. |
| |
| ▲ | tgv 3 days ago | parent [-] | | Except 'some condition' may change, can be long, or expensive, so you likely need an extra variable. |
|