Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Objects and Generics

Objects and Tuples in Nim

Learn how Nim groups data with object, ref object and tuple types, how construction and field access work, and why value and reference objects behave differently.

Real programs need to bundle values together: a user has a name and an age, a point has an x and a y. Nim gives you three tools for this: object, ref object and tuple. They look similar but behave differently when you copy them, and choosing the right one is the first design decision in most Nim programs.

A note on honesty before we start. This site cannot run the Nim compiler, so the Nim snippets here are read-only. To let you experiment, each lesson also has a runnable C stand-in that shows the same underlying idea (Nim compiles to C, so this is a faithful model of what happens in memory). Every stand-in is labelled. If you have Nim installed, paste the Nim snippets into a file and run them with nim r file.nim.

Value objects

An object is a record stored directly where you declare it, like a C struct. Assigning one to another variable copies every field.

NIM
type
  Point = object
    x, y: int

var a = Point(x: 1, y: 2)
var b = a        # a full copy
b.x = 99
echo a.x         # 1: a is unchanged
echo b.x         # 99

You construct an object by naming the type and giving fields as name: value pairs. Fields you leave out get their default value (0 for numbers, "" for strings, nil for references). Fields can be exported to other modules by adding a star: x*, y*: int.

The stand-in below shows what "copy on assignment" means in memory.

C C stand-in: value semantics

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.

Reference objects

A ref object lives on the heap, and a variable holds a pointer to it. Assigning copies the pointer, so both names refer to the same object. You get one with new or by calling the type as a constructor.

NIM
type
  Node = ref object
    value: int
    next: Node       # nil means "no next node"

let n = Node(value: 1)
let m = n            # same object, two names
m.value = 42
echo n.value         # 42

Use ref object when objects are shared, when they are large, when they need identity (two nodes with equal values are still different nodes), or when you need inheritance with runtime dispatch (see Inheritance and Methods). Use plain object for small plain data. Nim frees reference objects automatically, as explained in ARC and ORC.

C C stand-in: reference semantics

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.

Tuples

A tuple is a lightweight record. Two tuple types are the same type if their fields have the same types (and names), no declaration needed.

NIM
let person = (name: "Ada", age: 36)
echo person.name          # Ada
echo person[1]            # 36

proc minMax(a, b: int): (int, int) =
  if a < b: (a, b) else: (b, a)

let (lo, hi) = minMax(7, 3)   # unpacking
echo lo, " ", hi              # 3 7

Tuples are the idiomatic way to return several values from a proc. Prefer a named object once a record has a meaning of its own and appears in many signatures, because the declared name documents intent and lets you attach procs to it.

C C stand-in: returning two values

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.

Choosing between them

flowchart TD
  Q["Need to group values?"] --> S{"Shared or identity<br/>matters?"}
  S -->|yes| R["ref object"]
  S -->|no| T{"Named type reused<br/>across the program?"}
  T -->|yes| O["object"]
  T -->|no| U["tuple"]

A quick decision guide for grouping data in Nim.

Common mistakes: expecting a ref object assignment to copy (it aliases), and forgetting that a ref that was never created is nil, so reading a field raises a nil-access error.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens after var b = a when a is a plain object?

    Plain objects have value semantics, so assignment copies every field.
  2. 2. Which type gives two names that refer to the same instance?

    A ref object variable holds a pointer, so copying the variable copies the pointer.
  3. 3. How do you unpack a tuple into variables?

    Parentheses on the left side of let destructure a tuple.
  4. 4. What is the default value of an unset ref field?

    References default to nil, so check before reading fields.

Summary

  • object is a value type: assignment copies.
  • ref object is heap allocated: assignment shares.
  • tuple is a structural, lightweight record, ideal for multiple return values.
  • Construct with Type(field: value); unset fields get defaults.
  • Nim snippets are read-only on this site; the C stand-ins model the memory behavior.

Next: Inheritance and Methods