Nim Medium · Lesson 1 · On the house

Templates

Code substitution with template, untyped parameters, hygiene, and when to use them. Lesson 1 is free — on the house.

Lessons · Nim Medium · Lesson 1 of 10 · On the house

Templates

Code substitution with template, untyped parameters, hygiene, and when to use them.

Illustration for Nim
Lesson 1 is on the house.

A template is a hygienic code substitution: its body is pasted at the call site, then compiled.

Parameters are evaluated where they appear in the body, so untyped blocks can be passed in: template twice(body: untyped) = body; body.

Templates are good for small control-flow helpers (withLock, measure, retry) with zero call overhead.

Variables declared inside are hygienic (renamed) unless marked {.inject.}.

A parameter used twice is evaluated twice; bind it to a let first if it has side effects.

templates

import std/[times, monotimes]

template twice(body: untyped) =
  body
  body

template measure(label: string, body: untyped) =
  let t0 = getMonoTime()
  body
  let ms = (getMonoTime() - t0).inMilliseconds
  doAssert ms >= 0
  echo label, " done"

template withValue(v: int, body: untyped) =
  let it {.inject.} = v * 10
  body

var n = 0
twice: inc n
echo n
measure("sum"):
  var s = 0
  for i in 1..1000: s += i
  echo s
withValue(4):
  echo it + 2
Match this when you type.

Quiz

What does a template do at the call site?

Quiz

What lets a template variable be visible to the caller's block?

Quiz

Risk of using a parameter twice in a template?

Quiz

What does n equal after twice: inc n?

Check

Match the still for: Templates.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.