Skip to content

Mojo Materialization

The compiler can build values for you while it builds your program: numbers, strings, even whole lists (see Mojo Compile-Time Code). When run-time code uses one of those values, Mojo has to put a real copy of it into the running program. That step is called materialization. For small values it happens on its own. For bigger ones Mojo asks you to say so, and this short page shows how and why.

Numbers, Bools and strings are materialized for you. You can copy a comptime value into a var and change the copy as much as you like:

comptime LIMIT = 100
comptime RATE = 0.25
comptime TITLE = "Report"
def main():
var limit = LIMIT
limit += 1
var title = TITLE
title += "!"
print(limit, RATE * 2, title)

Output:

101 0.5 Report!

These types are cheap to copy (they’re ImplicitlyCopyable), so the compiler just drops the value into the program wherever you use it. A string literal like "Report" becomes a normal String when you put it in a var.

A List is different. Making a run-time copy means asking for memory and filling it, every time. Mojo won’t do that behind your back:

comptime NAMES: List[String] = ["Ada", "Bob", "Cy"]
def main():
for name in NAMES:
print(name)
hello.mojo:4:17: error: cannot materialize comptime value of type 'List[String]' to runtime because it is not 'ImplicitlyCopyable'
for name in NAMES:
^~~~~
hello.mojo:4:17: note: use 'materialize' to explicitly materialize the value
for name in NAMES:
^
materialize[ ]()
mojo: error: failed to parse the provided Mojo source module

The note shows the fix. materialize[NAMES]() makes one run-time copy, which you then use like any list:

comptime NAMES: List[String] = ["Ada", "Bob", "Cy"]
def main():
var names = materialize[NAMES]()
for name in names:
print(name)
names.append("Dee")
print(len(names), "names now")

Output:

Ada
Bob
Cy
4 names now

names is an ordinary List[String]. Changing it doesn’t touch NAMES, which stays fixed. This is the same idea as .copy() on a list: copies that cost something are always written out, so you can see where they happen. The materialize docs have the details.

Because materialize builds a new list each time it runs, where you put it matters. This works, but builds and throws away the whole list on every step:

def total_slow(steps: Int) -> Int:
comptime PRICES: List[Int] = [5, 8, 13]
var total = 0
for i in range(steps):
var prices = materialize[PRICES]() # a new list every time
total += prices[i % 3]
return total

Move it out of the loop and the list is built once:

def total_fast(steps: Int) -> Int:
comptime PRICES: List[Int] = [5, 8, 13]
var prices = materialize[PRICES]()
var total = 0
for i in range(steps):
total += prices[i % 3]
return total
def main():
print(total_fast(6))

Output:

52

That’s why Mojo makes you write materialize yourself: you decide when the memory gets used.

Often you don’t need the whole list at run time, only an answer about it. Ask the question at compile time with comptime (...), or loop with comptime for, and only the answers reach the program:

comptime PRIMES: List[Int] = [2, 3, 5, 7, 11, 13]
def main():
print("count:", comptime (len(PRIMES)))
print("biggest:", comptime (PRIMES[5]))
comptime for p in PRIMES:
print(p, end=" ")
print()

Output:

count: 6
biggest: 13
2 3 5 7 11 13

Each comptime (...) is worked out while building, and the comptime for becomes six print calls with the numbers filled in. No run-time list is ever made. This only works when the index is known while building: for an index from a var, you need a real list (or the lookup table below).

Sometimes you want a fixed table that run-time code reads with run-time indexes, like the number of days in each month. global_constant stores a compile-time value once, in the program’s read-only data, and gives you a reference to it:

from std.builtin.globals import global_constant
def days_in(month: Int) -> Int:
comptime DAYS: Array[Int, 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
ref days = global_constant[DAYS]()
if month < 1 or month > 12:
return 0
return days[month - 1]
def main():
print(days_in(2), days_in(12), days_in(13))

Output:

28 31 0

Nothing is built when days_in runs: days points straight at the stored table. Two rules:

  • Bind it with ref, not var. var days = global_constant[DAYS]() would try to copy the Array, and fails with “cannot be implicitly copied”.
  • It only works for self-contained values like Array of numbers. A List, Dict or String holds a pointer to other memory, so global_constant refuses it with “global_constant requires a type with trivial copy and destroy semantics”.
You have You need Use
A number, Bool or string It at run time Just use it: it materializes by itself
A compile-time List One answer (length, an item at a fixed index) comptime (...) or comptime for
A compile-time List A list to read or change at run time materialize[...](), once, outside loops
A fixed table of numbers Fast lookups with run-time indexes Array + global_constant, bound with ref

This program doesn’t compile. Make it print each color on its own line, and then 3 colors.

comptime COLORS: List[String] = ["red", "green", "blue"]
def main():
for c in COLORS:
print(c)
print(len(COLORS), "colors")

Hint: one materialize before the loop fixes both lines. Or, without any run-time list, use comptime for and comptime (...).

Show solution
comptime COLORS: List[String] = ["red", "green", "blue"]
def main():
var colors = materialize[COLORS]()
for c in colors:
print(c)
print(len(colors), "colors")

Output:

red
green
blue
3 colors

One run-time copy serves the loop and len. The no-list version, comptime for c in COLORS: plus comptime (len(COLORS)), prints the same thing.

Make a function points(place: Int) -> Int that returns the points for finishing 1st to 5th (10, 8, 6, 4, 2) and 0 for any other place. Store the points with global_constant.

Hint: copy the shape of days_in, with an Array[Int, 5].

Show solution
from std.builtin.globals import global_constant
def points(place: Int) -> Int:
comptime TABLE: Array[Int, 5] = [10, 8, 6, 4, 2]
ref table = global_constant[TABLE]()
if place < 1 or place > 5:
return 0
return table[place - 1]
def main():
print(points(1), points(3), points(9))

Output:

10 6 0

The table is stored once in the program, and every call reads it through ref table without building anything.

  • Materialization turns a compile-time value into a run-time one.
  • Numbers, Bools and strings materialize by themselves.
  • A compile-time List (or other non-ImplicitlyCopyable value) needs materialize[NAME](), which builds a new copy each time it runs.
  • Materialize once, outside loops, or skip it with comptime (...) and comptime for.
  • global_constant[TABLE]() stores a fixed Array once; bind it with ref. It doesn’t work for List, Dict or String.

Next up: SIMD, Mojo’s type for doing the same math on many numbers at once.

Quick check

1. comptime LIMIT = 100, then var x = LIMIT. What do you need to write?
2. Why is materialize[PRICES]() inside a loop a bad idea?
3. Which value can you store with global_constant?