Skip to main content

Mojo function

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:

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

def main():
print(half(UInt8(5))) # prints 2
print(half(Scalar[DType.bool](True))) # constraint failed:
# dtype must be numeric.
fn half[dtype: DType](a: Scalar[dtype]) -> Scalar[dtype]:
constrained[
dtype.is_numeric(),
"dtype must be numeric."
]()
return a / 2

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

Parameters:

  • cond (Bool): The bool value to assert.
  • msg (StringSlice[StaticConstantOrigin]): The message to display on failure.
  • *extra (StringSlice[StaticConstantOrigin]): Additional messages to concatenate to msg.

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.

Parameters:

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

Was this page helpful?