Defer 语句
使用 defer 语句代替 try finally 语句可以避免代码的复杂嵌套,从作用域的角度看也更加灵活。下面给了例子。
在 defer 之后的任意语句,都认为处在当前块的隐式 try 块中:
proc main =
var f = open("numbers.txt", fmWrite)
defer: close(f)
f.write "abc"
f.write "def"
重写为:
proc main =
var f = open("numbers.txt")
try:
f.write "abc"
f.write "def"
finally:
close(f)
当 defer 位于模板/宏的最外层作用域时,它的作用域将延伸到调用模板/宏的那个代码块中:
template safeOpenDefer(f, path) =
var f = open(path, fmWrite)
defer: close(f)
template safeOpenFinally(f, path, body) =
var f = open(path, fmWrite)
try: body # 若不使用 `defer` ,`body` 必须指定为参数
finally: close(f)
block:
safeOpenDefer(f, "/tmp/z01.txt")
f.write "abc"
block:
safeOpenFinally(f, "/tmp/z01.txt"):
f.write "abc" # 增加一级词法作用域
block:
var f = open("/tmp/z01.txt", fmWrite)
try:
f.write "abc" # 增加一级词法作用域
finally: close(f)
Nim 不允许在最顶层使用 defer 语句,因为不确定这样的语句涉及哪些内容。
当前内容版权归 vectorworkshopbaoerjie 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 vectorworkshopbaoerjie .