3 ms·
Not the commenter but which one of these is the defer generating? // option 1 try { fp = os.open(x) fp.read() } finally { fp.
by gw 6y ago
Not the commenter but which one of these is the defer generating?
// option 1
try {
fp = os.open(x)
fp.read()
}
finally {
fp.close()
}
// option 2
fp = os.open(x)
try {
fp.read()
}
finally {
fp.close()
}
Should we close if open fails? Maybe, maybe not, but with try/finally it is obvious which one it is doing.
- CodesInChaos 6y agoThe first one doesn't compile in any language that requires variables to be initialized before use.
- chomp 6y agoIn nim, it generates code analogous to option 2.
- gw 6y agoYou sure? https://forum.nim-lang.org/t/4022#25046 https://forum.nim-lang.org/t/4022#25046 edit: the docs seem to say you're right, maybe that forum post is outdated but it's from nim's author.
- jerf 6y agoThe first one is obviously wrong, which I mean in the sense that anyone who knows what defer is will know that, not in the sense that you've posted an obviously bad post (it is a fair question!). defer is a statement, not a declaration, and does not take effect until it is executed like any other statement. It follows standard structured programming rules; line 2 does not execute until line 1 is done. (A rule so simple and obvious we often don't think about, especially since structured programming has basically won and everything we use nowadays is structured, but it is still a rule that we use in programming.)