Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 36 ยท Memory and Concurrency

Value, Reference and Pointer Semantics in Nim

Learn how Nim passes arguments, what var parameters do, the difference between ref and ptr, when to use addr and unsafe pointers, and how openArray avoids copies.

Nim passes arguments to procedures by value in the language model, but the compiler is free to pass large immutable values by hidden reference, so you do not pay for copies you do not need. This lesson explains the rules and the four tools you have for sharing data: var parameters, ref, ptr and openArray.

All Nim snippets are read-only here. The C stand-ins model what the generated code does.

Immutable parameters by default

A parameter inside a proc is read-only. Writing to it is a compile error.

NIM
proc bump(x: int): int =
  # x += 1   # error: x is immutable
  x + 1

echo bump(4)   # 5

The caller's variable cannot change, so the compiler may pass big objects by pointer without telling you. You can treat every argument as a value.

var parameters

To let a proc modify the caller's variable, declare the parameter var. The caller must pass something mutable.

NIM
proc bump(x: var int) = inc x

var n = 4
bump n
echo n         # 5

This is Nim's reference parameter: no & or * at the call site and no null possible. The C equivalent is a pointer parameter:

C C stand-in: var is a non-null pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

ref and ptr

ref T ptr T
Memory Traced: freed automatically Untraced: you free it
Safety Safe, nil-checked on access Unsafe, like a C pointer
Created with new, constructor addr, alloc, create
Use for Normal shared data FFI, manual layouts, shared memory
NIM
var x = 10
let p = addr x          # ptr int, no ownership
p[] = 11                # dereference with []
echo x                  # 11

let r = new int         # ref int, managed
r[] = 5

addr x gives a pointer to a variable. Use it sparingly and never keep it past the variable's lifetime, as the stand-in shows by pointing at a local that is still alive:

C C stand-in: ptr and dereference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

openArray: borrowing a slice

openArray[T] accepts an array, a seq, or a slice of either, without copying. Use it for read-only input of unknown length.

NIM
proc sum(xs: openArray[int]): int =
  for x in xs: result += x

echo sum([1, 2, 3])
echo sum(@[4, 5])
echo sum(@[1, 2, 3, 4][1 .. 2])   # 5

An openArray is a pointer and a length under the hood, so passing it costs two machine words. This C stand-in shows the pair:

C C stand-in: pointer plus length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

result and lent

Inside a proc with a return type, the implicit result variable is the value to return, so there is no extra copy at the end. Return types can be lent T to borrow rather than copy (used for accessors like seq indexing), and sink T parameters take ownership; both are optimizations on top of the rules above. See Memory Management with ARC and ORC.

Common mistakes

  • Forgetting var and wondering why a change did not stick (the compiler normally stops you).
  • Keeping a ptr or addr to a seq element, then adding to the seq, which may reallocate.
  • Dereferencing a nil ref: check with if r != nil.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Can a proc modify a normal parameter?

    Parameters are immutable; use var to modify the caller's variable.
  2. 2. What is the main difference between ref and ptr?

    ref is traced and freed automatically; ptr is a raw pointer.
  3. 3. Which type accepts an array, a seq or a slice without copying?

    openArray is a view of a contiguous run of elements.
  4. 4. How do you get a pointer to a variable?

    addr takes the address and yields a ptr.

Summary

  • Parameters are immutable; var makes a mutable reference, never nil.
  • ref is managed and shared; ptr is raw and manual.
  • openArray borrows a pointer and a length.
  • addr and [] take and follow addresses; use them only for FFI and layouts.

Next: Threads and Channels