var_t_return.rst 939 B

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