Skip to content

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.

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:

9
2.5

The 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.

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:

9
2.5
pear

Read [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 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 module

The 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:

  • Comparable gives you <, >, <=, >= (and ==, since it builds on Equatable).
  • ImplicitlyCopyable lets you return a without 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.

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 module

a 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 (like List) can’t use the function.
  • Use Copyable and copy on purpose with return a.copy(). This accepts more types.

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 here
def bigger[T: Comparable & ImplicitlyCopyable](a: T, b: T) -> T:
^
mojo: error: failed to parse the provided Mojo source module

The 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.

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:

2
3

Equatable 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 pear

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:

20
no words yet

What to notice:

  • Inside the struct, the type is Self.T, just like value parameters are Self.rows on the parameters page.
  • comptime Element = Copyable & Deinitable gives a trait combination a name, so you don’t repeat it.
  • A field like List[Self.T] needs T to be Deinitable; without it Mojo says “field ‘items’ has non-‘Deinitable’ type ‘List[T]’”.
  • pop returns an Optional, so an empty stack gives None instead of crashing.

Stack[Int] and Stack[String] are two different types made from one definition.

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.5

It’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.

  • 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 T from the arguments, you have to write it: Stack[Int](), not Stack().

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).

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:

2
fig

One body handles both types. The compiler builds an Int version and a String version from it.

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_init
struct 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 1
right left

Pair(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 T can 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 T needs ImplicitlyCopyable (or Copyable plus .copy()), and keeping a T around often needs Deinitable.
  • Same T means the same type: bigger(an_int, a_float) doesn’t compile.
  • Inside a generic struct the type is Self.T; name trait combos with comptime 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

1. Why does def bigger[T: AnyType](a: T, b: T) -> T fail when it uses a > b?
2. What happens with bigger(count, price) where count is an Int and price is a Float64?
3. Inside struct Stack[T: Copyable & Deinitable], how do you write the element type?
4. Which is the same as def show[T: Writable](value: T)?