Mojo Parameters
You’ve been writing square brackets for a while: List[Int], Array[Int, 3], Dict[String, Int]. Those brackets hold parameters, Mojo’s name for inputs that are known at compile time. Normal round-bracket inputs are arguments, and they arrive at run time. This page shows how to add parameters to your own functions and structs, and how to decide which kind of input to use.
Parameters and arguments
Section titled “Parameters and arguments”In most languages, “parameter” and “argument” mean almost the same thing. Mojo gives them two different jobs:
| Brackets | Known when? | Example | |
|---|---|---|---|
| Parameter | [ ] |
While the program is being built | [count: Int] |
| Argument | ( ) |
While the program runs | (msg: String) |
Here’s a function with one of each:
def repeat[count: Int](msg: String): for _ in range(count): print(msg)
def main(): repeat[3]("Hi") repeat[1]("Bye")Output:
HiHiHiByecount goes in square brackets, both in the definition and in the call. It’s written like an argument (a name, a colon and a type), but it lives in its own list in front of the round brackets.
The Mojo manual’s page on parameters puts it simply: in Mojo, “parameter” always means a compile-time value, and “argument” always means a run-time value.
A parameter must be known while building
Section titled “A parameter must be known while building”The compiler needs a parameter’s value before the program runs. A value that lives in a var isn’t known yet:
def repeat[count: Int](msg: String): for _ in range(count): print(msg)
def main(): var times = 2 repeat[times]("Hi")hello.mojo:7:12: error: invalid call to 'repeat': cannot use a dynamic value in a parameter list repeat[times]("Hi") ~~~~~~ ^~~~~hello.mojo:1:5: note: function declared heredef repeat[count: Int](msg: String): ^mojo: error: failed to parse the provided Mojo source module“Dynamic value” means a value that’s only known at run time. Literals like 2 work, and so do comptime values (comptime TIMES = 2, then repeat[TIMES]("Hi")). If the number really comes from the user or a file, it has to be an argument instead.
Leaving a parameter out entirely is also an error: repeat("Hi") gives “failed to infer parameter ‘count’”. The compiler has no way to guess how many times you meant.
Each value makes its own version
Section titled “Each value makes its own version”When you call repeat[3], the compiler builds a version of repeat where count is simply 3. Call repeat[1] too, and it builds a second version. This is called specialization: every distinct parameter value gets its own copy of the function, made to measure.
You can even keep a specialized version under a name:
def power[exponent: Int](base: Int) -> Int: var result = 1 for _ in range(exponent): result *= base return result
def main(): print(power[2](7)) comptime cube = power[3] print(cube(2), cube(4))Output:
498 64comptime cube = power[3] gives a name to the version of power where exponent is 3. cube is an ordinary function that takes one argument.
Default and keyword parameters
Section titled “Default and keyword parameters”Parameters can have default values and be passed by name, just like arguments:
def speak[times: Int = 1, sound: String = "woof"](): for _ in range(times): print(sound)
def main(): speak() speak[2]() speak[sound="meow"]()Output:
woofwoofwoofmeowspeak() uses both defaults. speak[2]() sets times. speak[sound="meow"]() skips times and sets only sound by name. Notice the empty (): speak has no arguments, but you still need the round brackets to call it.
Parameters on a struct
Section titled “Parameters on a struct”Structs can take parameters too. That’s what Array[Int, 3] is: a struct with two parameters, a type and a length. Here’s your own:
struct Grid[rows: Int, cols: Int]: comptime cells = Self.rows * Self.cols var data: List[Int]
def __init__(out self): self.data = List[Int](length=Self.cells, fill=0)
def show(self): print(Self.rows, "x", Self.cols, "=", len(self.data), "cells")
def main(): var small = Grid[3, 4]() small.show() print(Grid[2, 5].cells) print(small.rows)Output:
3 x 4 = 12 cells103A few new things here:
- Inside the struct, you reach a parameter with
Self.:Self.rows,Self.cols. comptime cells = ...inside a struct is a compile-time member: a value worked out from the parameters. EveryGrid[3, 4]hascellsequal to12, without storing it in a field.- You can read parameters and compile-time members from the type (
Grid[2, 5].cells) or from a value (small.rows).
Different parameters, different types
Section titled “Different parameters, different types”Grid[3, 4] and Grid[4, 3] are two different types, not two values of one type. You can’t mix them:
struct Grid[rows: Int, cols: Int]: var data: List[Int]
def __init__(out self): self.data = List[Int](length=Self.rows * Self.cols, fill=0)
def main(): var a = Grid[3, 4]() var b = Grid[4, 3]() a = bhello.mojo:10:9: error: cannot implicitly convert 'Grid[Int(4), Int(3)]' value to 'Grid[Int(3), Int(4)]' a = b ^mojo: error: failed to parse the provided Mojo source moduleThat’s the same reason List[Int] and List[String] can’t be swapped. The parameters are part of the type’s name, and the compiler checks them.
Letting Mojo work out the parameters
Section titled “Letting Mojo work out the parameters”You often don’t have to write parameters at the call site. If a parameter appears in an argument’s type, the compiler can read it from the value you pass. This is called parameter inference:
def first_of[size: Int](values: Array[Int, size]) -> Int: print("size is", size) return values[0]
def main(): var three: Array[Int, 3] = [7, 8, 9] var five = Array[Int, 5](fill=1) print(first_of(three)) print(first_of(five))Output:
size is 37size is 51three has the type Array[Int, 3], so in first_of(three) the compiler knows size is 3. It isn’t reading the run-time contents; it’s reading the type, which was fixed when the program was built.
Reading signatures with //
Section titled “Reading signatures with //”In the standard library docs you’ll see a // inside the square brackets. Parameters before the // are infer-only: you never pass them, Mojo always works them out from the others.
def show_info[dtype: DType, //, value: Scalar[dtype]](): print(value, dtype)
def main(): show_info[Float64(2.5)]() show_info[Int32(7)]()Output:
2.5 float647 int32You pass only value. Its type (Float64 or Int32) tells Mojo what dtype is. Without the // you’d have to write show_info[DType.float64, Float64(2.5)](). You won’t write // often yourself, but now you can read it when you see it.
Parameter or argument?
Section titled “Parameter or argument?”Ask yourself: do you know the value when you write the code?
- Yes, and it shapes the code (a size, a count, a mode, a type): make it a parameter. You get a version made for that value, and mistakes show up while building.
- No, it comes from the user, a file or a calculation: make it an argument. One version of the function handles every value.
When in doubt, use an argument. It’s simpler, and you can still switch to a parameter later if you find you need it.
Practice
Section titled “Practice”1. A greeting machine
Section titled “1. A greeting machine”Write greet[name: String, times: Int = 1]() that prints Hello, <name>! times times. Call it once with only a name and once with times=2.
Hint: parameters with defaults go at the end, just like arguments.
Show solution
def greet[name: String, times: Int = 1](): for _ in range(times): print("Hello, " + name + "!")
def main(): greet["Ada"]() greet["Bob", times=2]()Output:
Hello, Ada!Hello, Bob!Hello, Bob!Strings work as parameters too, as long as they’re known while building. greet["Bob", times=2]() passes the first one by position and the second by name.
2. A bucket with a fixed size
Section titled “2. A bucket with a fixed size”Write a struct Bucket[capacity: Int] with a List[String] field. Its add(item) method appends the item and returns True, or returns False without adding when the bucket is full. Make a Bucket[2] and try to add three items.
Hint: compare len(self.items) with Self.capacity.
Show solution
struct Bucket[capacity: Int]: var items: List[String]
def __init__(out self): self.items = List[String]()
def add(mut self, item: String) -> Bool: if len(self.items) >= Self.capacity: return False self.items.append(item) return True
def main(): var b = Bucket[2]() print(b.add("apple")) print(b.add("pear")) print(b.add("plum")) print(len(b.items), "of", b.capacity)Output:
TrueTrueFalse2 of 2The capacity is part of the type: a Bucket[2] can never hold three items, and you can read the limit with b.capacity.
- Parameters go in
[ ]and are known while building; arguments go in( )and arrive at run time. - A parameter needs a value the compiler knows: a literal or a
comptimevalue, never avar. - Each distinct parameter value gets its own specialized version of the function or struct.
- Parameters can have defaults and be passed by name.
- Inside a struct, use
Self.namefor parameters;comptimemembers are values worked out from them. Grid[3, 4]andGrid[4, 3]are different types.- Mojo can infer parameters from argument types; parameters before
//are always inferred.
Next up: generics, where the parameter is a type, so one function works for Int, Float64 and String.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Parameterization: the official guide to parameters, inference, infer-only parameters and parameterized
comptimevalues. - Compile-time evaluation: how the compiler works out parameter values while building.
- How to read the API docs: what
[ ],( ),//,/and*mean in standard library signatures. Arrayin the standard library: a real struct with a type parameter and a length parameter.