Skip to main content
Log in

Mojo function

constrained

constrained[cond: Bool, msg: StringLiteral = "param assertion failed"]()

Compile time checks that the condition is true.

The constrained is similar to static_assert in C++ and is used to introduce constraints on the enclosing function. In Mojo, the assert places a constraint on the function. The message is displayed when the assertion fails.

Example:

from sys.info import num_physical_cores

def main():
alias cores_to_use = 2
multicore_check[cores_to_use]()

def multicore_check[cores: Int]():
constrained[
cores <= num_physical_cores(),
"build failed: not enough cores"
]()
constrained[
cores >= 2,
"at least two cores are required"
]()

from sys.info import num_physical_cores

def main():
alias cores_to_use = 2
multicore_check[cores_to_use]()

def multicore_check[cores: Int]():
constrained[
cores <= num_physical_cores(),
"build failed: not enough cores"
]()
constrained[
cores >= 2,
"at least two cores are required"
]()

Parameters:

  • cond (Bool): The bool value to assert.
  • msg (StringLiteral): The message to display on failure.

constrained[cond: Bool, msg: String]()

Compile time checks that the condition is true.

The constrained is similar to static_assert in C++ and is used to introduce constraints on the enclosing function. In Mojo, the assert places a constraint on the function. The message is displayed when the assertion fails, and takes a generalized string.

Example:

from sys.info import num_physical_cores

def main():
alias cores_to_use = 2
multicore_check[cores_to_use]()

def multicore_check[cores: Int]():
constrained[
cores <= num_physical_cores(),
"build failed: not enough cores"
]()
constrained[
cores >= 2,
"at least two cores are required"
]()



**Parameters:**

*<b>cond</b> (`Bool`): The bool value to assert.
*<b>msg</b> (`String`): The message to display on failure.


</div>


</section>
from sys.info import num_physical_cores

def main():
alias cores_to_use = 2
multicore_check[cores_to_use]()

def multicore_check[cores: Int]():
constrained[
cores <= num_physical_cores(),
"build failed: not enough cores"
]()
constrained[
cores >= 2,
"at least two cores are required"
]()



**Parameters:**

*<b>cond</b> (`Bool`): The bool value to assert.
*<b>msg</b> (`String`): The message to display on failure.


</div>


</section>