Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 36 ยท Macros and Templates

Templates in Nim

Learn how Nim templates work as hygienic code substitution, untyped and typed parameters, passing blocks, and building your own control structures such as withLock.

A template is a way to give a name to a pattern of code. When you call it, the compiler substitutes the template body at the call site before type checking. Templates are Nim's lightweight metaprogramming: simpler than macros, and often all you need for things like timing a block, repeating code or creating a custom if.

Nim code in this lesson is read-only on this site; the C stand-ins show the equivalent preprocessor-style substitution.

A first template

NIM
template square(x: untyped): untyped =
  x * x

echo square(4)        # 16

Unlike a proc, a template does not create a function call. The expression square(4) is replaced by 4 * 4. Two consequences follow: there is no call overhead, and arguments can be code that is not evaluated the way a proc argument would be.

typed and untyped parameters

  • typed: the argument is type checked before substitution, so the template can inspect its type.
  • untyped: the argument is not checked yet, so it may refer to names that do not exist until the template creates them.
NIM
template declareCounter(name: untyped) =
  var name = 0            # introduces a variable named by the caller

declareCounter(hits)
inc hits
echo hits                 # 1

By default template variables are hygienic: a variable declared inside the template does not leak into the caller. The {.inject.} pragma deliberately exposes a name, and {.gensym.} makes it unique to avoid clashes.

Why substitution matters

A proc evaluates arguments once. A template pastes the expression wherever the parameter appears, which can evaluate it several times. The classic C macro pitfall is real here as well, unless the argument is bound to a let first.

C C stand-in: substitution evaluates arguments again

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.

In Nim, write let v = x as the first line of a template when the argument must run once. Nim templates are hygienic, so unlike C macros they cannot capture variables by accident.

Passing a block of code

A template can take a final untyped parameter that receives a whole indented block. This is how you write your own control structures.

NIM
template repeat(n: int, body: untyped) =
  for _ in 1 .. n:
    body

repeat 3:
  echo "hello"

Another common use is timing or logging around code:

NIM
import std/times

template timeIt(label: string, body: untyped) =
  let start = cpuTime()
  body
  echo label, ": ", cpuTime() - start, "s"

timeIt "sum":
  var s = 0
  for i in 1 .. 1_000_000: s += i
C C stand-in: a repeat construct

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.

Templates versus procs, macros and iterators

Need Use
A normal function proc
Zero overhead wrapper, custom block syntax template
Inspect or rewrite syntax trees macro
Lazy sequence of values iterator

Templates also work as operator or accessor sugar (template [](...)). Because they are expanded at the call site, error messages can point inside the expansion; keep templates short and well named.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the compiler do with a template call?

    Templates are code substitution done before and during type checking.
  2. 2. What does untyped allow?

    An untyped argument is not type checked before substitution.
  3. 3. What is the effect of hygiene?

    Hygienic templates avoid accidental name capture unless you use inject.
  4. 4. How do you give a template a block of code?

    The block becomes the last untyped argument.

Summary

  • Templates substitute code at the call site: no call overhead.
  • typed arguments are checked first; untyped are not.
  • Hygiene keeps template names private; {.inject.} exposes them.
  • A trailing untyped parameter lets you define new control structures.
  • Reach for a macro when you must inspect syntax, not just reuse it.

Next: Macros and the AST