Skip to content

Mojo Constraints

Traits say what a type must be able to do. But sometimes the problem is a value: a batch size of 0, a table size that isn’t a power of two, a range where the start is after the end. Mojo lets you write those rules down as constraints, checked while the program is built. A wrong value then stops the build with a clear message, instead of crashing later. This page covers the two tools for it, where and comptime assert, and how constraints work with types too.

Here’s a function that tells you how many batches you need for some number of items:

def batches[size: Int](total: Int) -> Int:
return (total + size - 1) // size
def main():
print(batches[10](95))
print(batches[32](95))

Output:

10
3

It works, but nothing stops someone from writing batches[0](95), which divides by zero, or batches[-5](95), which gives nonsense. size is a parameter, so its value is known while building. That means the compiler could check it, if you tell it the rule.

Add where and a condition after the return type:

def batches[size: Int](total: Int) -> Int where size > 0:
return (total + size - 1) // size
def main():
print(batches[10](95))
print(batches[32](95))

Output:

10
3

The good calls work exactly as before. Now try a bad one:

def batches[size: Int](total: Int) -> Int where size > 0:
return (total + size - 1) // size
def main():
print(batches[0](95))
hello.mojo:5:11: error: invalid call to 'batches': violated constraint
print(batches[0](95))
^~~~~~~
hello.mojo:1:49: note: constraint declared here evaluated to False, expected '(size > Int(0))'
def batches[size: Int](total: Int) -> Int where size > 0:
^
hello.mojo:1:5: note: function declared here
def batches[size: Int](total: Int) -> Int where size > 0:
^
mojo: error: failed to parse the provided Mojo source module

The error points at the call, the place where the mistake was made, and the note shows the rule that was broken. The program never runs, so the division by zero can’t happen.

If you know C++20 “concepts”, you might expect the word requires. Mojo uses where; requires isn’t a keyword.

Join conditions with and, and use as many parameters as you need:

def batches[size: Int](total: Int) -> Int where size > 0 and size <= 1024:
return (total + size - 1) // size
def window[start: Int, end: Int]() -> Int where start < end:
return end - start
def main():
print(batches[100](950))
print(window[2, 9]())

Output:

10
7

batches[2000](950) is now an error too, and so is window[9, 2]().

The other tool goes inside the function. A comptime assert checks a condition while building and stops with your own message when it’s false:

def table_size[n: Int]() -> Int:
comptime assert n > 0, "n must be positive"
comptime assert n & (n - 1) == 0, "n must be a power of two"
return n
def main():
print(table_size[8]())
print(table_size[12]())
hello.mojo:6:5: error: function instantiation failed
def main():
^
hello.mojo:8:25: note: call expansion failed with parameter value(s): ("n": 12)
print(table_size[12]())
^
hello.mojo:1:5: note: function instantiation failed
def table_size[n: Int]() -> Int:
^
hello.mojo:3:5: note: constraint failed: n must be a power of two
comptime assert n & (n - 1) == 0, "n must be a power of two"
^
mojo: error: failed to run the pass manager

The useful line is the last note:: “constraint failed: n must be a power of two”, and the one above it tells you which call caused it ("n": 12). (n & (n - 1) == 0 is a common trick: it’s true only for powers of two.) Remove the table_size[12] line and the program prints 8.

So what’s the difference from where?

where comptime assert
Where it goes In the signature In the body (must be inside a function)
Who must keep the rule The caller The function itself
Error message “violated constraint”, with the rule Your own message

Use where for rules a caller can understand and should keep. Use comptime assert for checks inside your own code, or when a custom message helps. You already met comptime assert with -D settings in Mojo Feature Toggles.

Here’s a catch. When a generic function calls a constrained one, Mojo needs proof that the rule holds. It won’t look at every possible value to find out:

def batches[size: Int](total: Int) -> Int where size > 0:
return (total + size - 1) // size
def report[size: Int](total: Int):
print(batches[size](total), "batches")
def main():
report[10](95)
hello.mojo:5:11: error: invalid call to 'batches': lacking evidence to prove correctness
print(batches[size](total), "batches")
^~~~~~~
hello.mojo:1:5: note: cannot prove constraint for candidate
def batches[size: Int](total: Int) -> Int where size > 0:
^
hello.mojo:1:49: note: constraint declared here needs evidence for '(size > Int(0))'
def batches[size: Int](total: Int) -> Int where size > 0:
^
hello.mojo:5:11: note: provide evidence for the constraint here to aid in candidate selection
print(batches[size](total), "batches")
^
mojo: error: failed to parse the provided Mojo source module

Inside report, size could be anything, so Mojo can’t promise batches that it’s positive. The Mojo manual’s page on constraints calls this giving the compiler knowledge. You have three ways to give it:

def batches[size: Int](total: Int) -> Int where size > 0:
return (total + size - 1) // size
# 1. Pass the rule on to your own callers.
def report_a[size: Int](total: Int) where size > 0:
print(batches[size](total))
# 2. Check it, and handle the other case.
def report_b[size: Int](total: Int):
comptime if size > 0:
print(batches[size](total))
else:
print("no batches for size", size)
# 3. Promise it yourself.
def report_c[size: Int](total: Int):
comptime assert size > 0, "size must be positive"
print(batches[size](total))
def main():
report_a[10](95)
report_b[10](95)
report_b[0](95)
report_c[32](95)

Output:

10
10
no batches for size 0
3
  • where on your own function: inside report_a, the compiler knows size > 0 because nobody could call it otherwise.
  • comptime if: inside the if branch, the condition is known to be true. report_b accepts any size and deals with the bad ones. (More on comptime if in Compile-Time If & Loops.)
  • comptime assert: after the assert, the condition is known.

Conditions can also ask about types, with conforms_to(T, SomeTrait). This lets a generic struct offer a method only for some T:

@fieldwise_init
struct Box[T: Copyable & Deinitable]:
var value: Self.T
def is_bigger_than(self, other: Self.T) -> Bool where conforms_to(Self.T, Comparable):
return self.value > other
@fieldwise_init
struct Secret(Copyable):
var code: Int
def main():
var number = Box(5)
print(number.is_bigger_than(3))
var hidden = Box(Secret(42))
print(hidden.value.code)

Output:

True
42

Any Copyable type can go in a Box, but is_bigger_than only exists for boxes whose T is Comparable. Box(Secret(42)) is fine; calling hidden.is_bigger_than(Secret(1)) would fail with “violated constraint … expected ‘conforms_to(T, Comparable)’”.

You can put the same kind of condition on the traits a struct conforms to. This is called conditional conformance:

@fieldwise_init
struct Box[T: Copyable & Deinitable](
Writable where conforms_to(T, Writable)
):
var value: Self.T
@fieldwise_init
struct Secret(Copyable):
var code: Int
def main():
var hidden = Box(Secret(42))
print(hidden)
hello.mojo:13:11: error: invalid call to 'print': an element of 'values' with type 'Box[Secret]' does not conform to trait 'Writable'; either prove the conformance with 'conforms_to', or add conformance
print(hidden)
~~~~~ ^
hello.mojo:3:5: note: failed constraint
Writable where conforms_to(T, Writable)
^
mojo: error: failed to parse the provided Mojo source module

(We trimmed the lines that point into the standard library.) A Box[Int] is Writable and prints as Box[SIMD[DType.int, 1]](value=5) (Int shows under its full name, SIMD[DType.int, 1], which you’ll meet in Mojo SIMD). A Box[Secret] isn’t, because Secret isn’t. The standard library uses this pattern everywhere: a List[T] can be printed only when its T can.

You want to… Use
Say what a type must be able to do A trait: [T: Comparable]
Limit a parameter’s value, and make callers keep the rule where size > 0
Check something inside your function, with your own message comptime assert
Offer a method or trait only for some T where conforms_to(T, Trait)
Check a value that’s only known at run time Not a constraint: raise an error (Mojo Errors)

The last row matters: constraints only work on values the compiler knows. For user input or file contents, use errors.

Write percent[p: Int](total: Float64) -> Float64 that returns p percent of total, with a where clause that only allows p from 0 to 100. Call it with 25, then try 150 and read the error.

Hint: two comparisons joined with and. Turn p into a float with Float64(p).

Show solution
def percent[p: Int](total: Float64) -> Float64 where p >= 0 and p <= 100:
return total * Float64(p) / 100.0
def main():
print(percent[25](80.0))

Output:

20.0

percent[150](80.0) stops the build with “violated constraint”, and the note shows the condition that was false.

This program doesn’t compile (“lacking evidence”). Fix show_percent so it works for every p: print the result for a real percentage, and <p> is not a percentage otherwise.

def percent[p: Int](total: Float64) -> Float64 where p >= 0 and p <= 100:
return total * Float64(p) / 100.0
def show_percent[p: Int](total: Float64):
print(percent[p](total))
def main():
show_percent[50](30.0)
show_percent[150](30.0)

Hint: inside a comptime if, its condition counts as proof.

Show solution
def percent[p: Int](total: Float64) -> Float64 where p >= 0 and p <= 100:
return total * Float64(p) / 100.0
def show_percent[p: Int](total: Float64):
comptime if p >= 0 and p <= 100:
print(percent[p](total))
else:
print(p, "is not a percentage")
def main():
show_percent[50](30.0)
show_percent[150](30.0)

Output:

15.0
150 is not a percentage

The comptime if uses exactly the same condition as percent, so inside the branch the compiler has its proof. A where on show_percent would also compile, but then show_percent[150] would be an error.

  • A constraint is a rule about parameters, checked while building.
  • where cond after the signature makes callers keep the rule; breaking it gives “violated constraint” at the call.
  • comptime assert cond, "message" checks inside a function body, with your own message.
  • Calling a constrained function from generic code needs evidence: pass the where on, use comptime if, or comptime assert.
  • Mojo doesn’t do the math on conditions: size >= 2 doesn’t prove size > 0.
  • conforms_to(T, Trait) in a where gates methods, and in the trait list gives conditional conformance.
  • Run-time values can’t be constraints: raise an error for those.

Next up: compile-time if and loops, choosing and repeating code while building with comptime if and comptime for.

Quick check

1. What happens with batches[0](95) when batches has where size > 0?
2. A function has where size >= 2 and calls one that needs size > 0. What happens?
3. Which one goes inside the function body and lets you write your own error message?
4. What does struct Box[T: ...](Writable where conforms_to(T, Writable)) mean?