Mojo Constants
Every var in Mojo can change. Sometimes you want the opposite: a value that’s fixed forever, like the number of players in a game, a tax rate, or a maximum file size. Mojo makes these with the comptime keyword. The name says what it does: the value is worked out at compile time, before your program even starts, and it can’t change while the program runs.
Your first constant
Section titled “Your first constant”Write comptime, a name, = and a value:
comptime MAX_PLAYERS = 4comptime GAME_NAME = "Space Race"
def main(): print(GAME_NAME, "allows", MAX_PLAYERS, "players")Output:
Space Race allows 4 playersUnlike var, a comptime value can live outside any function, at the top of the file. That makes it a good place for settings that the whole file uses.
The names are in UPPER_SNAKE_CASE. Mojo doesn’t require it, and the official docs use lowercase names too, but it’s a habit many people bring from Python and C: a name in capitals tells the reader “this never changes”.
Constants can’t be changed
Section titled “Constants can’t be changed”Try to assign a new value and the compiler stops you:
comptime MAX_PLAYERS = 4
def main(): MAX_PLAYERS = 5 print(MAX_PLAYERS)hello.mojo:4:5: error: expression must be mutable in assignment MAX_PLAYERS = 5 ^~~~~~~~~~~mojo: error: failed to parse the provided Mojo source module“Mutable” means “can be changed”. A constant isn’t, so the assignment is rejected before the program runs. You also can’t define the same constant twice in one place: a second comptime MAX_PLAYERS = 6 in the same file gives invalid redefinition of 'MAX_PLAYERS'.
Adding a type
Section titled “Adding a type”Like var, you can give a constant a type annotation:
comptime PI: Float64 = 3.14159comptime MAX_LEVEL: UInt8 = 99
def main(): var radius = 2.0 print(PI * radius * radius) print("Top level:", MAX_LEVEL)Output:
12.56636Top level: 99Without a type, a constant keeps the exact value you wrote, and it takes on a concrete type (like Int or Float64) when you use it. An annotation is useful when you want a specific size, like UInt8 here.
Using a constant in a variable
Section titled “Using a constant in a variable”A constant is often a starting value. When you copy it into a var, the variable is a normal variable that you can change. The constant stays as it was:
comptime STARTING_LIVES = 3
def main(): var lives = STARTING_LIVES lives -= 1 print("Lives left:", lives) print("Every game starts with", STARTING_LIVES)Output:
Lives left: 2Every game starts with 3Turning a compile-time value into a runtime value like this is called materialization. You don’t need the word yet, but you’ll see it in error messages and in the Mojo manual’s page on materialization.
The compiler does the math
Section titled “The compiler does the math”The value of a constant can be an expression, and the compiler works it out before the program runs:
comptime SECONDS_PER_MINUTE = 60comptime SECONDS_PER_DAY = SECONDS_PER_MINUTE * 60 * 24comptime GREETING = "Hello, " + "world"
def main(): print(SECONDS_PER_DAY) print(GREETING)Output:
86400Hello, worldIt can even call your own functions:
def square(n: Int) -> Int: return n * n
comptime BOARD_CELLS = square(8)
def main(): print("A chess board has", BOARD_CELLS, "cells")Output:
A chess board has 64 cellssquare(8) runs inside the compiler, and the program gets the finished 64. Most normal code can run at compile time. The exceptions, according to the Mojo manual’s page on compile-time evaluation, are things that depend on the running machine: reading files, calling C libraries, and functions that can raise errors.
But only with values known in advance
Section titled “But only with values known in advance”Since constants are worked out before the program runs, they can’t depend on anything that only exists while it runs, like a variable:
def main(): var players = 5 comptime LIMIT = players * 2 print(LIMIT)hello.mojo:3:22: error: cannot use a dynamic value in comptime initializer comptime LIMIT = players * 2 ^~~~~~~mojo: error: failed to parse the provided Mojo source moduleA “dynamic value” is one that’s only known at runtime. If a value comes from the user, a file or a calculation on variables, use var. If you know it when you write the code, comptime is a good fit.
Constants inside functions
Section titled “Constants inside functions”You can also declare a constant inside a function. It belongs to that function, and it can even hide a file-level constant with the same name:
comptime LIMIT = 10
def show_limit(): comptime LIMIT = 20 print("inside show_limit:", LIMIT)
def main(): print("inside main:", LIMIT) show_limit()Output:
inside main: 10inside show_limit: 20main sees the file-level LIMIT, and show_limit sees its own. Like shadowing with var, this works but can confuse readers, so use it sparingly.
Practice
Section titled “Practice”1. Shop settings
Section titled “1. Shop settings”Create two constants at the top of the file: TAX_RATE (0.2) and SHOP_NAME ("Corner Shop"). In main, compute the tax on a price of 50.0 and print Corner Shop tax: 10.0.
Hint: comptime lines go outside main.
Show solution
comptime TAX_RATE = 0.2comptime SHOP_NAME = "Corner Shop"
def main(): var price = 50.0 var tax = price * TAX_RATE print(SHOP_NAME, "tax:", tax)Output:
Corner Shop tax: 10.0TAX_RATE and SHOP_NAME are fixed for the whole file. tax is a normal variable, because it’s worked out from price at runtime.
2. Minutes in a week
Section titled “2. Minutes in a week”Make a constant MINUTES_PER_WEEK that the compiler works out from 60, 24 and 7, and print it.
Hint: a comptime value can be any expression of literals and other constants.
Show solution
comptime MINUTES_PER_HOUR = 60comptime MINUTES_PER_WEEK = MINUTES_PER_HOUR * 24 * 7
def main(): print(MINUTES_PER_WEEK)Output:
10080The multiplication happens inside the compiler, so the program just prints a ready-made number.
3. Fix the constant
Section titled “3. Fix the constant”This program doesn’t compile. Make it print Next level: 6 without changing the line comptime LEVEL = 5.
comptime LEVEL = 5
def main(): LEVEL += 1 print("Next level:", LEVEL)Hint: copy the constant into a var first.
Show solution
comptime LEVEL = 5
def main(): var level = LEVEL level += 1 print("Next level:", level)Output:
Next level: 6A constant can’t change, but a variable that starts with its value can.
comptime NAME = valuemakes a constant that’s worked out at compile time and can’t change.- Constants can live at the top of a file (unlike
var, which must be in a function) or inside a function. - Assigning to a constant fails with
expression must be mutable in assignment. - You can add a type:
comptime PI: Float64 = 3.14159. - The value can be an expression or a function call, as long as it doesn’t use runtime values like variables.
- Copying a constant into a
vargives you a normal variable you can change.aliasis gone; usecomptime.
Next up: integer overflow, what happens when a number doesn’t fit in its type.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo manual: Compile-time evaluation:
comptimevalues, their scope, and what code can run at compile time. - Mojo manual: Materialization: how compile-time values become runtime values.
- Mojo manual: Variables: how
varandcomptimediffer. StringAPI docs: showscomptimeused for an unchangeable string, and the constantsStringitself defines (likeString.DIGITS).