IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

constrained

constrained[cond: Bool, msg: StringSlice[StaticConstantOrigin], *extra: StringSlice[StaticConstantOrigin]]()

Asserts that the condition must be true at compile time.

The constrained() function introduces a compile-time constraint on the enclosing function. If the condition is true at compile time, the constraint has no effect. If the condition is false, compilation fails and the message is displayed.

This is similar to static_assert in C++. It differs from debug_assert(), which is a run-time assertion.

Example:

def half[dtype: DType](a: Scalar[dtype]) -> Scalar[dtype]:
comptime assert dtype.is_numeric(), "dtype must be numeric."
return a / 2

def main() raises:
print(half(UInt8(5))) # prints 2
print(half(Scalar[DType.bool](True))) # constraint failed:
# dtype must be numeric.

Deprecated: Use comptime assert instead

Parameters:

constrained[cond: Bool]()

Asserts that the condition must be true at compile time.

The constrained() function introduces a compile-time constraint on the enclosing function. If the condition is true at compile time, the constraint has no effect. If the condition is false, compilation fails and a generic message is displayed.

This is similar to static_assert in C++. It differs from debug_assert(), which is a run-time assertion.

For an example, see the first overload.

Deprecated: Use comptime assert instead

Parameters:

  • cond (Bool): The bool value to assert.