zlacker

[parent] [thread] 7 comments
1. gf000+(OP)[view] [source] 2025-08-22 12:02:01
Making it lexical scope would make both of these solvable, and would be clear for anyone reading it.

You can just introduce a new scope wherever you want with {} in sane languages, to control the required behavior as you wish.

replies(2): >>lowmag+75 >>tgv+c6
2. lowmag+75[view] [source] 2025-08-22 12:34:37
>>gf000+(OP)
You can start a new scope with `{}` in go. If I have a bunch of temp vars I'll declare the final result outside the braces and then do the work inside. But lately days I'll just write a function. It's clearer and easier to test.
3. tgv+c6[view] [source] 2025-08-22 12:40:08
>>gf000+(OP)
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.
replies(3): >>iainme+yF >>atombe+QF1 >>raluk+UQ2
◧◩
4. iainme+yF[view] [source] [discussion] 2025-08-22 15:49:58
>>tgv+c6
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).

replies(1): >>tgv+3G2
◧◩
5. atombe+QF1[view] [source] [discussion] 2025-08-22 21:17:13
>>tgv+c6
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)
◧◩◪
6. tgv+3G2[view] [source] [discussion] 2025-08-23 06:31:16
>>iainme+yF
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...

◧◩
7. raluk+UQ2[view] [source] [discussion] 2025-08-23 08:46:51
>>tgv+c6
Having lexicial scope it is same as -> defer fn{if(some condition) x() }() within scope.
replies(1): >>tgv+793
◧◩◪
8. tgv+793[view] [source] [discussion] 2025-08-23 12:39:40
>>raluk+UQ2
Except 'some condition' may change, can be long, or expensive, so you likely need an extra variable.
[go to top]