Mojo Generics
Say you want a function that returns the bigger of two values, and you want it for Int, for Float64 and for String. You could write it three times. Generics let you write it once: the type becomes a parameter, and the compiler makes a version for each type you actually use. This page shows how, and why Mojo always asks you to say what the type must be able to do.
The problem: the same code, twice
Section titled “The problem: the same code, twice”Here’s the copy-and-paste way:
def bigger_int(a: Int, b: Int) -> Int: if a > b: return a return b
def bigger_float(a: Float64, b: Float64) -> Float64: if a > b: return a return b
def main(): print(bigger_int(3, 9)) print(bigger_float(2.5, 1.5))Output:
92.5The two bodies are identical. Only the type changed. Overloading would let both share the name bigger, but you’d still be writing the body once per type, and fixing a bug means fixing it everywhere.
One function, any type
Section titled “One function, any type”Make the type a parameter. By convention it’s called T:
def bigger[T: Comparable & ImplicitlyCopyable](a: T, b: T) -> T: if a > b: return a return b
def main(): print(bigger(3, 9)) print(bigger(2.5, 1.5)) print(bigger(String("pear"), String("apple")))Output:
92.5pearRead [T: Comparable & ImplicitlyCopyable] as “for any type T that can be compared and copied”. Then a: T, b: T and -> T use that type. You never pass T yourself: in bigger(3, 9) the compiler sees two Ints and works out that T is Int. Behind the scenes it builds a bigger for Int, one for Float64 and one for String, just like the hand-written versions above.
Why the trait is required
Section titled “Why the trait is required”Why not just write [T: AnyType], meaning “any type at all”? Try it:
def bigger[T: AnyType](a: T, b: T) -> T: if a > b: return a return b
def main(): print(bigger(3, 9))hello.mojo:2:10: error: 'T' does not implement the '__gt__' method if a > b: ~ ^mojo: error: failed to parse the provided Mojo source moduleThe compiler checks the function once, for every possible T, before it knows which types you’ll call it with. If T could be anything, > might not exist for it. The traits after the colon are your promise about what T can do, and the only things you may do with a and b are things those traits provide:
Comparablegives you<,>,<=,>=(and==, since it builds onEquatable).ImplicitlyCopyablelets youreturn awithout writing.copy().
This is the biggest difference from Python. In Python, def bigger(a, b) accepts anything, and you find out at run time if > doesn’t work. In Mojo, a generic function that compiles works for every type that has the listed traits, and calling it with a type that doesn’t is a compile error.
The common traits page lists the standard traits you’ll reach for most.
Copying inside generic code
Section titled “Copying inside generic code”Drop ImplicitlyCopyable and see what happens:
def bigger[T: Comparable](a: T, b: T) -> T: if a > b: return a return b
def main(): print(bigger(3, 9))hello.mojo:3:16: error: value of type 'T' cannot be implicitly copied, it does not conform to 'ImplicitlyCopyable' return a ^hello.mojo:4:12: error: value of type 'T' cannot be implicitly copied, it does not conform to 'ImplicitlyCopyable' return b ^mojo: error: failed to parse the provided Mojo source modulea is borrowed from the caller, so returning it means making a copy. For Int that’s free, but T might be a big List, so Mojo won’t copy it silently. You have two fixes:
- Add
ImplicitlyCopyable(as above). Simple, but now types that only copy on request (likeList) can’t use the function. - Use
Copyableand copy on purpose withreturn a.copy(). This accepts more types.
Same T means the same type
Section titled “Same T means the same type”Both arguments are T, so they must be the same type:
def bigger[T: Comparable & ImplicitlyCopyable](a: T, b: T) -> T: if a > b: return a return b
def main(): var count: Int = 3 var price: Float64 = 2.5 print(bigger(count, price))hello.mojo:9:25: error: invalid call to 'bigger': value passed to 'b' cannot be converted from 'Float64' to 'Int' print(bigger(count, price)) ~~~~~~ ^~~~~hello.mojo:1:5: note: function declared heredef bigger[T: Comparable & ImplicitlyCopyable](a: T, b: T) -> T: ^mojo: error: failed to parse the provided Mojo source moduleThe first argument fixed T as Int, and a Float64 isn’t an Int. Mojo doesn’t quietly convert between number types here, which is good: you decide. Convert one yourself (Float64(count)), or set T by hand: bigger[Float64](3, 2.5) works, because the literal 3 can become a Float64.
Generic functions over lists
Section titled “Generic functions over lists”Generics work with collections too. This function counts how often a value appears, in any list whose items can be compared with ==:
def count_matches[T: Equatable](items: List[T], target: T) -> Int: var count = 0 for item in items: if item == target: count += 1 return count
def main(): var words: List[String] = ["a", "b", "a"] var prices: List[Float64] = [1.5, 2.5, 1.5, 1.5] print(count_matches(words, "a")) print(count_matches(prices, 1.5))Output:
23Equatable is all this function needs, because it only uses ==. Keep the trait list as short as your code allows: every extra trait is one more thing a type must have before it can use your function.
When you create a local variable of type T and keep it around, you’ll also need Deinitable, which promises the compiler it can clean that value up. Without it you get “‘best’ abandoned without being explicitly destroyed … consider adding trait conformance to Deinitable”:
def largest[T: Comparable & ImplicitlyCopyable & Deinitable](items: List[T]) -> T: var best = items[0] for item in items: if item > best: best = item return best
def main(): var a: List[Int] = [3, 9, 2] var b: List[String] = ["kiwi", "apple", "pear"] print(largest(a), largest(b))Output:
9 pearGeneric structs
Section titled “Generic structs”A struct can take a type parameter too. That’s how List[T] works. Here’s a small stack:
comptime Element = Copyable & Deinitable
struct Stack[T: Element]: var items: List[Self.T]
def __init__(out self): self.items = List[Self.T]()
def push(mut self, var item: Self.T): self.items.append(item^)
def pop(mut self) -> Optional[Self.T]: if len(self.items) == 0: return None return self.items.pop()
def main(): var nums = Stack[Int]() nums.push(10) nums.push(20) print(nums.pop().value()) var words = Stack[String]() if not words.pop(): print("no words yet")Output:
20no words yetWhat to notice:
- Inside the struct, the type is
Self.T, just like value parameters areSelf.rowson the parameters page. comptime Element = Copyable & Deinitablegives a trait combination a name, so you don’t repeat it.- A field like
List[Self.T]needsTto beDeinitable; without it Mojo says “field ‘items’ has non-‘Deinitable’ type ‘List[T]’”. popreturns anOptional, so an empty stack givesNoneinstead of crashing.
Stack[Int] and Stack[String] are two different types made from one definition.
The Some[...] shortcut
Section titled “The Some[...] shortcut”When a type parameter is used by just one argument, you can skip naming it. Some[Trait] means “some type that has this trait”:
def show(value: Some[Writable]): print("->", value)
def main(): show(3) show("hello") show(2.5)Output:
-> 3-> hello-> 2.5It’s the same as def show[T: Writable](value: T). Use the long form when two arguments must share a type (like bigger), or when you need to write T again in the return type.
What generics can’t do (yet)
Section titled “What generics can’t do (yet)”- No list of mixed types.
List[Writable]doesn’t compile: a list holds one concrete type. A trait isn’t a type you can store. - No guessing. If the compiler can’t work out
Tfrom the arguments, you have to write it:Stack[Int](), notStack().
The Mojo manual’s page on parameterized declarations goes further, including value and type parameters mixed together and traits that a struct only has when its T has them (covered in Mojo Constraints).
Practice
Section titled “Practice”1. Smallest of three
Section titled “1. Smallest of three”Write a generic smallest(a, b, c) that returns the smallest of three values of the same type. Test it with Ints and with Strings.
Hint: use the same traits as bigger, and compare step by step.
Show solution
def smallest[T: Comparable & ImplicitlyCopyable](a: T, b: T, c: T) -> T: if a <= b and a <= c: return a if b <= c: return b return c
def main(): print(smallest(7, 2, 5)) print(smallest(String("pear"), String("fig"), String("plum")))Output:
2figOne body handles both types. The compiler builds an Int version and a String version from it.
2. A generic pair
Section titled “2. A generic pair”Write a struct Pair[T: Copyable & Deinitable] with fields first and second, and a method swapped() that returns a new Pair with the two values swapped. Use @fieldwise_init so you get the initializer for free.
Hint: the return type can be Self, and fields need .copy() because T is only Copyable.
Show solution
@fieldwise_initstruct Pair[T: Copyable & Deinitable]: var first: Self.T var second: Self.T
def swapped(self) -> Self: return Self(self.second.copy(), self.first.copy())
def main(): var p = Pair(1, 2).swapped() print(p.first, p.second) var q = Pair[String]("left", "right").swapped() print(q.first, q.second)Output:
2 1right leftPair(1, 2) lets Mojo infer T as Int from the arguments. Self inside the struct means “this same Pair type, with the same T”.
- A generic function or struct takes a type as a parameter:
def bigger[T: Comparable & ImplicitlyCopyable](a: T, b: T) -> T. - The traits after the colon list what
Tcan do; you can only use what they provide. - Mojo checks generic code once for every possible
T, so mistakes show up while building, not at run time. - Returning or storing a
TneedsImplicitlyCopyable(orCopyableplus.copy()), and keeping aTaround often needsDeinitable. - Same
Tmeans the same type:bigger(an_int, a_float)doesn’t compile. - Inside a generic struct the type is
Self.T; name trait combos withcomptime Element = A & B. Some[Trait]is a short way to write a type parameter used by one argument.
Next up: constraints, how to limit which values and types a generic function or struct accepts with where and comptime assert.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Parameterized declarations: the official guide to type parameters, choosing traits, generic structs and
Some. - Traits: how traits work and how to write your own.
- Parameterization: parameter inference and how parameterized types are built.
Listin the standard library: a real generic struct, with the traits it asks of its items.