Version: 1.1.0

Metaprogramming

Mojo metaprogramming is ordinary Mojo that runs while the program is compiling. Parameters, comptime, and traits are the tools.

Essentials

  • A parameter in square brackets is fixed before runtime.
  • comptime forces a block or value to be evaluated by the compiler.
  • Traits describe behavior that parameters must have.
  • The same source can specialize for a CPU, a GPU, or a data type.
  • Reflection reads fields and methods without writing them out by hand.

Example

fn repeat[count: Int](msg: String):
    comptime:
        for _ in range(count):
            print(msg)

Keep in mind

If a value can change at runtime, it is an argument, not a parameter. Parameters are for facts the compiler can exploit.