var_t_return.rst 899 B

123456789101112131415161718192021
  1. Memory safety for returning by ``var T`` is ensured by a simple borrowing
  2. rule: If ``result`` does not refer to a location pointing to the heap
  3. (that is in ``result = X`` the ``X`` involves a ``ptr`` or ``ref`` access)
  4. then it has to be deviated by the routine's first parameter:
  5. .. code-block:: nim
  6. proc forward[T](x: var T): var T =
  7. result = x # ok, deviated from the first parameter.
  8. proc p(param: var int): var int =
  9. var x: int
  10. # we know 'forward' provides a view into the location deviated by
  11. # its first argument 'x'.
  12. result = forward(x) # Error: location is derived from ``x``
  13. # which is not p's first parameter and lives
  14. # on the stack.
  15. In other words, the lifetime of what ``result`` points to is attached to the
  16. lifetime of the first parameter and that is enough knowledge to verify
  17. memory safety at the callsite.