Skip to content

Mojo Feature Toggles

A feature toggle is a switch you flip when you build your program, to include or leave out a piece of code. Think “verbose logging on”, “use the fast path”, “this build is for macOS”. In Mojo, you set these switches on the command line with -D, read them in your code, and the compiler builds only the parts you asked for. You’ve already met two of them: -D TRACE in Mojo Debugging and -D ASSERT=all in Mojo Debug Asserts. This lesson shows how they work.

is_defined["name"]() tells you whether -D name was passed. Pair it with comptime if:

from std.sys import is_defined
def main():
print("Starting the app")
comptime if is_defined["verbose"]():
print("verbose: loading settings")
print("verbose: settings loaded")
print("Ready")

Output:

Starting the app
Ready

Now run it with the switch on:

Terminal window
mojo run -D verbose app.mojo
Starting the app
verbose: loading settings
verbose: settings loaded
Ready

Two things are new here:

  • -D verbose defines a name for this build. It’s a bit like setting an environment variable, except the compiler reads it, not the running program.
  • comptime if is an if that the compiler decides while building. When the condition is false, the code inside isn’t skipped at run time: it’s left out of the program completely.

The square brackets in is_defined["verbose"]() mean the name is a compile-time value. That’s why it has to be a literal string, not a variable.

A define can also carry a value: -D mode=release. Read it with get_defined_string, giving a default for when it’s missing:

from std.sys import get_defined_string
def main():
comptime mode = get_defined_string["mode", "debug"]()
print("mode:", mode)
comptime if mode == "release":
print("using the fast path")
else:
print("using the extra-careful path")

Output:

mode: debug
using the extra-careful path

With mojo run -D mode=release app.mojo it prints mode: release and using the fast path. You can write -D mode=release or -Dmode=release; both work.

comptime mode = ... stores the value as a compile-time constant (see Mojo Constants), so comptime if can use it.

There’s a reader for each kind of value:

from std.sys import get_defined_int, get_defined_bool
def main():
comptime threads = get_defined_int["threads", 4]()
comptime color = get_defined_bool["color"]()
print("threads:", threads)
print("color:", color)

Output:

threads: 4
color: False

And with values on the command line:

Terminal window
mojo run -D threads=8 -D color=on app.mojo
threads: 8
color: True

A few rules worth knowing:

Function Missing define Notes
is_defined["x"]() False Ignores the value: -D x and -D x=0 both give True
get_defined_string["x", "default"]() the default Without a default, a missing define is a compile error
get_defined_int["x", 4]() the default Only plain base-10 numbers: -D x=8 works, -D x=0x10 doesn’t
get_defined_bool["x"]() False 1, true, True, TRUE, on, On, ON mean True; anything else (even yes) is False

That last row is a classic trap: -D color=yes gives False. And -D color with no value doesn’t compile for get_defined_bool, because there’s nothing to read. Use is_defined for plain on/off switches.

Leave out the default, and the define becomes required. Forget it, and the program doesn’t build:

from std.sys import get_defined_string
def main():
comptime server = get_defined_string["server"]()
print("connecting to", server)
hello.mojo:3:5: error: function instantiation failed
def main():
^
hello.mojo:3:5: note: call expansion failed with parameter value(s): (...)
<unknown>:0: note: define 'server' does not exist, please provide it via -D
mojo: error: failed to run the pass manager

The useful line is the last note:: “define ‘server’ does not exist, please provide it via -D”. (We trimmed two lines that point into the standard library.) A value of the wrong kind fails the same way: -D threads=eight with get_defined_int gives “define ‘threads’ is not an integer”.

Mojo checks these at compile time, so a typo in a build setting can’t sneak into a running program.

Put -D before the file name. Anything after the file name is passed to your program as its own arguments, so the compiler never sees it:

Terminal window
mojo run -D mode=release app.mojo # mode is release
mojo run app.mojo -D mode=release # mode is still debug!

Defines work with mojo build too, and the value is baked into the program you build:

Terminal window
mojo build -D mode=release app.mojo
./app # prints mode: release

Running ./app -D mode=debug won’t change it: the decision was made when you compiled.

Some toggles come from the compiler’s own options. std.sys.compile lets you read them:

from std.sys.compile import OptimizationLevel, DebugLevel
def main():
print("optimization level:", OptimizationLevel.level)
print("debug info:", DebugLevel.level)

Output:

optimization level: 3
debug info: none

With mojo run -O0 -g app.mojo, the same program prints optimization level: 0 and debug info: full. The default is full optimization (3) and no debug info. Mojo Debugging showed when you’d want -O0 -g.

ASSERT is also a built-in define, and the one you’ll use most: -D ASSERT=all, warn, safe (the default) or none decide which asserts run.

CompilationTarget answers questions about the system you’re compiling for, so you can pick code per operating system or CPU:

from std.sys import CompilationTarget
def main():
comptime if CompilationTarget.is_linux():
print("built for Linux")
elif CompilationTarget.is_macos():
print("built for macOS")
comptime if CompilationTarget.is_x86():
print("x86 CPU")
elif CompilationTarget.is_arm():
print("ARM CPU")

Output (on our Linux x86 machine):

built for Linux
x86 CPU

On an Apple silicon Mac you’d see built for macOS and ARM CPU. There’s no Windows check, because Mojo only runs on Windows through WSL, which is Linux. The feature toggles page in the Mojo docs lists more checks, like is_apple_silicon(), CPU features and GPUs.

When a define has limits, check them with comptime assert. A bad value then stops the build, with your message:

from std.sys import get_defined_int
def main():
comptime size = get_defined_int["size", 16]()
comptime assert size <= 64, "size must be 64 or less"
print("buffer size:", size)

Output:

buffer size: 16

Try mojo run -D size=100 app.mojo and it doesn’t compile:

app.mojo:3:5: error: function instantiation failed
def main():
^
app.mojo:5:5: note: constraint failed: size must be 64 or less
comptime assert size <= 64, "size must be 64 or less"
^
mojo: error: failed to run the pass manager

Write a program that prints Hello! by default and Hola! when built with -D lang=es.

Hint: get_defined_string["lang", "en"]() and a comptime if.

Show solution
from std.sys import get_defined_string
def main():
comptime lang = get_defined_string["lang", "en"]()
comptime if lang == "es":
print("Hola!")
else:
print("Hello!")

Output:

Hello!

mojo run -D lang=es greet.mojo prints Hola!. Any other value, or none, gives Hello!.

Read retries with get_defined_int, default 3. Stop the build with a clear message if it’s below 1 or above 10. Print will retry 3 times.

Hint: two conditions joined with and in one comptime assert.

Show solution
from std.sys import get_defined_int
def main():
comptime retries = get_defined_int["retries", 3]()
comptime assert retries >= 1 and retries <= 10, "retries must be 1 to 10"
print("will retry", retries, "times")

Output:

will retry 3 times

With -D retries=0 the build fails with constraint failed: retries must be 1 to 10, so a bad setting never reaches a running program.

  • A feature toggle is a switch you set at build time with -D name or -D name=value.
  • is_defined["name"]() checks whether a switch was passed; comptime if leaves the other code out entirely.
  • get_defined_string, get_defined_int and get_defined_bool read values; give a default, or the define is required.
  • get_defined_bool only accepts 1, true or on (any case) as True, and yes is False.
  • -D goes before the file name, and mojo build bakes the value into the program.
  • Read compiler settings with OptimizationLevel and DebugLevel, the platform with CompilationTarget, and check limits with comptime assert.

Next up: compiler errors, what Mojo’s error messages mean and how to fix the most common ones.

Quick check

1. What does comptime if is_defined["verbose"](): do when you build without -D verbose?
2. You run mojo run -D color=yes app.mojo. What does get_defined_bool["color"]() give?
3. Why does mojo run app.mojo -D mode=release not switch to release mode?
4. What happens with get_defined_string["server"]() (no default) when you don't pass -D server=...?