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.
Your first toggle
Section titled “Your first toggle”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 appReadyNow run it with the switch on:
mojo run -D verbose app.mojoStarting the appverbose: loading settingsverbose: settings loadedReadyTwo things are new here:
-D verbosedefines a name for this build. It’s a bit like setting an environment variable, except the compiler reads it, not the running program.comptime ifis anifthat 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.
Reading a value
Section titled “Reading a value”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: debugusing the extra-careful pathWith 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.
Numbers and true/false
Section titled “Numbers and true/false”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: 4color: FalseAnd with values on the command line:
mojo run -D threads=8 -D color=on app.mojothreads: 8color: TrueA 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.
When a define is required
Section titled “When a define is required”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 faileddef 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 -Dmojo: error: failed to run the pass managerThe 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.
Where -D goes
Section titled “Where -D goes”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:
mojo run -D mode=release app.mojo # mode is releasemojo 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:
mojo build -D mode=release app.mojo./app # prints mode: releaseRunning ./app -D mode=debug won’t change it: the decision was made when you compiled.
Settings the compiler fills in
Section titled “Settings the compiler fills in”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: 3debug info: noneWith 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.
Which machine am I building for?
Section titled “Which machine am I building for?”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 Linuxx86 CPUOn 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.
Stop bad settings early: comptime assert
Section titled “Stop bad settings early: comptime assert”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: 16Try mojo run -D size=100 app.mojo and it doesn’t compile:
app.mojo:3:5: error: function instantiation faileddef 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 managerPractice
Section titled “Practice”1. A greeting in two languages
Section titled “1. A greeting in two languages”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!.
2. A checked retry count
Section titled “2. A checked retry count”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 timesWith -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 nameor-D name=value. is_defined["name"]()checks whether a switch was passed;comptime ifleaves the other code out entirely.get_defined_string,get_defined_intandget_defined_boolread values; give a default, or the define is required.get_defined_boolonly accepts1,trueoron(any case) asTrue, andyesisFalse.-Dgoes before the file name, andmojo buildbakes the value into the program.- Read compiler settings with
OptimizationLevelandDebugLevel, the platform withCompilationTarget, and check limits withcomptime assert.
Next up: compiler errors, what Mojo’s error messages mean and how to fix the most common ones.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo compilation feature toggles: the official guide to
-D,comptime if, platform checks and built-in defines. std.sysmodule:is_defined, theget_defined_*functions andCompilationTarget.- Compile-time evaluation: how
comptimevalues andcomptime ifwork. mojo runreference: the-D,-Oand-goptions.