Var返回类型
proc,转换器或迭代器可能返回一个 var 类型,这意味着返回的值是一个左值,并且可以由调用者修改:
- var g = 0
- proc writeAccessToG(): var int =
- result = g
- writeAccessToG() = 6
- assert g == 6
如果隐式引入的指针可用于访问超出其生命周期的位置,则这是一个静态错误:
- proc writeAccessToG(): var int =
- var g = 0
- result = g # 错误!
For iterators, a component of a tuple return type can have a var type too:
- iterator mpairs(a: var seq[string]): tuple[key: int, val: var string] =
- for i in 0..a.high:
- yield (i, a[i])
在标准库中,返回 var 类型的例程的每个名称都以每个约定的前缀 m 开头。 Memory safety for returning by var T is ensured by a simple borrowing rule: If result does not refer to a location pointing to the heap (that is in result = X the X involves a ptr or ref access) then it has to be deviated by the routine's first parameter:
- proc forward[T](x: var T): var T =
- result = x # ok, deviated from the first parameter.
- proc p(param: var int): var int =
- var x: int
- # we know 'forward' provides a view into the location deviated by
- # its first argument 'x'.
- result = forward(x) # Error: location is derived from ``x``
- # which is not p's first parameter and lives
- # on the stack.
In other words, the lifetime of what result points to is attached to the lifetime of the first parameter and that is enough knowledge to verify memory safety at the callsite.
未来的方向
Nim的更高版本可以使用如下语法更准确地了解借用规则:
- proc foo(other: Y; container: var X): var T from container
这里 var T from container 明确地暴露了该位置不同于第二个形参(在本例中称为'container')。 语法 var T from p 指定一个类型 varTy [T,2] ,它与 varTy [T,1] 不兼容。