Mojo Compile-Time If & Loops
A normal if decides while the program runs. A comptime if decides while the program is being built, and the branches that lose are left out of the program completely. Its partner comptime for repeats a piece of code while building, so the finished program has several copies instead of a loop. You met comptime if with -D settings in Mojo Feature Toggles. This page shows where both really shine: inside generic code.
comptime if in a generic function
Section titled “comptime if in a generic function”Say you want a function that tells you what kind of type it got. The type is a parameter, so it’s known while building, and comptime if can look at it:
def describe[T: AnyType](): comptime if T == Int: print("a whole number") elif T == Float64: print("a decimal number") elif conforms_to(T, Writable): print("something printable") else: print("something else")
struct Secret: var code: Int
def __init__(out self, code: Int): self.code = code
def main(): describe[Int]() describe[Float64]() describe[String]() describe[Secret]()Output:
a whole numbera decimal numbersomething printablesomething elseTwo kinds of conditions show up here:
T == Intasks “isTexactly this type?”.conforms_to(T, Writable)asks “doesThave this trait?”.
Write comptime once, before the if. The elif and else branches belong to it and don’t need their own comptime. For describe[Int], the program that gets built only contains print("a whole number"). The other three branches simply aren’t there.
Why a normal if isn’t enough
Section titled “Why a normal if isn’t enough”Here’s a function that prints a value if it can, and a placeholder if it can’t. With a normal if, it doesn’t compile:
def show[T: AnyType](value: T): if conforms_to(T, Writable): print(value) else: print("<hidden>")
def main(): show(42)hello.mojo:3:15: error: invalid call to 'print': an element of 'values' with type 'T' does not conform to trait 'Writable'; either prove the conformance with 'conforms_to', or add conformance print(value) ~~~~~ ^mojo: error: failed to parse the provided Mojo source module(We trimmed the lines that point into the standard library.) A normal if keeps both branches in the program, so print(value) has to work for every possible T, and it doesn’t. The error even says what to do: prove the conformance. That’s exactly what comptime if does:
def show[T: AnyType](value: T): comptime if conforms_to(T, Writable): print(value) else: print("<a", reflect[T].base_name(), "value>")
struct Secret: var code: Int
def __init__(out self, code: Int): self.code = code
def main(): show(42) show("hello") show(Secret(7))Output:
42hello<a Secret value>Inside the comptime if branch, the compiler knows T is Writable, so print(value) is allowed. (reflect[T].base_name() gives the type’s name as text; Mojo Reflection covers it.) This “the condition counts as proof” idea is the same one you saw in Mojo Constraints.
The condition must be known while building
Section titled “The condition must be known while building”A comptime if can only use things the compiler knows: parameters, comptime values, literals, types. A var doesn’t qualify:
def main(): var score = 5 comptime if score > 3: print("big")hello.mojo:3:17: error: cannot use a dynamic value in 'comptime if' condition comptime if score > 3: ^~~~~mojo: error: failed to parse the provided Mojo source moduleFor values that come from the running program, use a normal if. That’s still the right choice almost all the time.
comptime for: repeat code while building
Section titled “comptime for: repeat code while building”A comptime for loop is unrolled: the compiler copies the body once per step, with the loop variable replaced by a fixed value each time. So the loop variable is a compile-time value, and you can use it where a parameter is needed:
def power[exponent: Int](base: Int) -> Int: var result = 1 for _ in range(exponent): result *= base return result
def main(): comptime for i in range(4): print("2 to the power", i, "is", power[i](2))Output:
2 to the power 0 is 12 to the power 1 is 22 to the power 2 is 42 to the power 3 is 8power[i] needs i while building. In a normal for, i only exists at run time, and you’d get “cannot use a dynamic value in type parameter”. With comptime for, the program that gets built is as if you’d written four print lines by hand, with power[0], power[1], power[2] and power[3].
The thing you loop over must be known while building too: range(4), range(SIZE) with a comptime SIZE, or a parameter. range(n) with a var n gives “cannot use a dynamic value in ‘for’ iterator expression”.
You can also loop over a list of literal values:
def main(): comptime for word in ["red", "green", "blue"]: print(word, "has", word.byte_length(), "letters")Output:
red has 3 lettersgreen has 5 lettersblue has 4 lettersSkipping and stopping
Section titled “Skipping and stopping”continue and break work inside a comptime for. To stop at a step decided while building, put the break under a comptime if:
def main(): comptime for i in range(10): comptime if i == 1: continue comptime if i == 4: break print("step", i)Output:
step 0step 2step 3Step 1 is skipped and the loop stops at 4, so only three copies of the body end up in the program.
Looping over arguments of different types
Section titled “Looping over arguments of different types”Here’s where comptime for is the only tool that works. A function can take a variadic pack: any number of arguments, each of its own type. You write it as *Ts: Writable in the parameters and *args: *Ts in the arguments:
def show_all[*Ts: Writable](*args: *Ts): comptime for i in range(len(Ts)): print(i, "->", args[i])
def main(): show_all(1, "two", 3.5, True)Output:
0 -> 11 -> two2 -> 3.53 -> TrueTs is the list of argument types (Int, String, Float64, Bool here), and len(Ts) is how many there are, known while building. Each copy of the loop body works with one argument of one known type. A normal for a in args doesn’t compile (“‘VariadicPack[False, Ts]’ does not implement the ‘iter’ method”), because one loop body can’t handle four different types. Ts[i] is the i-th type, so you can combine this with comptime if Ts[i] == Int: to treat some types differently.
When to use them (and when not)
Section titled “When to use them (and when not)”comptime if costs nothing at run time: the losing branches are gone. Use it to pick code by type, by parameter value, or by build setting.
comptime for is different. Every step is a copy of the body, so a 1,000-step comptime for puts 1,000 copies in your program and makes the build slower. The Mojo manual’s page on compile-time evaluation recommends it only for loops with small bodies and few steps. Use it when:
- the loop variable has to be a parameter (like
power[i]), - you’re looping over types or a variadic pack,
- or you’ve measured that unrolling a short, hot loop helps.
For everything else, a normal for is the right tool.
Practice
Section titled “Practice”1. Name that type
Section titled “1. Name that type”Write label[T: AnyType]() -> String that returns "whole number" for Int, "decimal" for Float64, "text" for String, and "other" for anything else. Print the labels for Int, String and Bool.
Hint: one comptime if with two elif branches, and a return after it for the “other” case.
Show solution
def label[T: AnyType]() -> String: comptime if T == Int: return "whole number" elif T == Float64: return "decimal" elif T == String: return "text" return "other"
def main(): print(label[Int]()) print(label[String]()) print(label[Bool]())Output:
whole numbertextotherFor label[Bool], none of the branches is built, so the function is just return "other".
2. Count the numbers
Section titled “2. Count the numbers”Write count_numbers(*args) that takes any number of Writable arguments and returns how many of them are Int or Float64. Test it with count_numbers(1, "two", 3.5, True, 7).
Hint: loop with comptime for i in range(len(Ts)) and test Ts[i] with comptime if.
Show solution
def count_numbers[*Ts: Writable](*args: *Ts) -> Int: var count = 0 comptime for i in range(len(Ts)): comptime if Ts[i] == Int or Ts[i] == Float64: count += 1 return count
def main(): print(count_numbers(1, "two", 3.5, True, 7))Output:
3The counting happens in normal run-time code (count += 1), but which arguments get a count += 1 is decided while building. For this call, the built function adds 1 exactly three times.
comptime ifdecides while building; the losing branches are left out of the program.- Conditions can test types:
T == Intandconforms_to(T, Trait). Inside the branch, the compiler knows the condition is true. - A normal
ifkeeps both branches, so code that only works for someTneedscomptime if. comptime forunrolls a loop: the body is copied once per step, and the loop variable can be used as a parameter.- Conditions and loop ranges must be known while building: no
vars. - Loop over a variadic pack with
comptime for i in range(len(Ts));Ts[i]is each argument’s type. - Keep
comptime forloops short;@parameter if/@parameter forare gone, usecomptime.
Next up: reflection, how to ask a type for its name, its fields and their types while building.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Compile-time evaluation: the official guide to
comptime if,comptime forand how unrolling works. - Parameterization: parameterized functions that use
comptime for, and variadic parameters. - Comptime constraints and assertions: how a
comptime ifcondition counts as knowledge for constraints. std.sysin the standard library:is_defined, platform checks and other values thatcomptime ifoften tests.