Var return type
A proc, converter or iterator may return a var type which means that the returned value is an l-value and can be modified by the caller:
var g = 0
proc writeAccessToG(): var int =
result = g
writeAccessToG() = 6
assert g == 6
It is a static error if the implicitly introduced pointer could be used to access a location beyond its lifetime:
proc writeAccessToG(): var int =
var g = 0
result = g # Error!
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])
In the standard library every name of a routine that returns a var type starts with the prefix m per convention.
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 derived from the routine’s first parameter:
proc forward[T](x: var T): var T =
result = x # ok, derived from the first parameter.
proc p(param: var int): var int =
var x: int
# we know 'forward' provides a view into the location derived from
# 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.
Future directions
Later versions of Nim can be more precise about the borrowing rule with a syntax like:
proc foo(other: Y; container: var X): var T from container
Here var T from container explicitly exposes that the location is derived from the second parameter (called ‘container’ in this case). The syntax var T from p specifies a type varTy[T, 2] which is incompatible with varTy[T, 1].