Mojo Overloading
Because every Mojo argument has a fixed type, a function that takes an Int can’t also take a String. When you want one name to work with several kinds of input, you write several versions of the function, each with its own argument types. That’s called overloading. Python doesn’t have it (a second def with the same name just replaces the first), so it may be new to you, but it’s simple to use.
Same name, different types
Section titled “Same name, different types”Here are four functions, all called describe. Each one takes a different type:
def describe(x: Int): print("an Int:", x)
def describe(x: Float64): print("a Float64:", x)
def describe(x: String): print("a String:", x)
def describe(x: Bool): print("a Bool:", x)
def main(): describe(42) describe(3.5) describe("hello") describe(True)Output:
an Int: 42a Float64: 3.5a String: helloa Bool: TrueMojo looks at what you pass and calls the version that fits. 42 goes to the Int version, 3.5 to the Float64 version, and so on. The group of functions that share a name is called an overload set.
Different versions can return different types, too. This is fine because the arguments are different:
def double(x: Int) -> Int: return x * 2
def double(x: String) -> String: return x + x
def main(): print(double(21)) print(double("ha"))Output:
42hahaSame name, different number of arguments
Section titled “Same name, different number of arguments”Overloads can also differ in how many arguments they take. One version can even call another:
def biggest(a: Int, b: Int) -> Int: return a if a > b else b
def biggest(a: Int, b: Int, c: Int) -> Int: return biggest(biggest(a, b), c)
def main(): print(biggest(3, 8)) print(biggest(3, 8, 5))Output:
88The three-argument version reuses the two-argument one, so the comparison is written only once.
How Mojo picks a version
Section titled “How Mojo picks a version”The choice is made when the program is built, not while it runs. Mojo looks at the number of arguments, their keywords and their types, and picks the version that needs the fewest conversions. It never looks at the return type.
Literals have a natural match. A whole number like 1 fits Int best, and 1.0 fits Float64 best:
def show(x: Int): print("Int")
def show(x: Float64): print("Float64")
def main(): show(1) show(1.0) var n = 3 show(Float64(n))Output:
IntFloat64Float64When you want a specific version, convert the value yourself, like Float64(n) here. That’s the general fix for any overload trouble.
When nothing fits
Section titled “When nothing fits”If no version accepts your arguments, Mojo lists every candidate and says why it didn’t fit:
def total(a: Int, b: Int) -> Int: return a + b
def total(a: Float64, b: Float64) -> Float64: return a + b
def main(): var x: Int = 2 var y: Float64 = 1.5 print(total(x, y))hello.mojo:10:11: error: no matching function in call to 'total' print(total(x, y)) ^~~~~hello.mojo:1:5: note: candidate not viable: value passed to 'b' cannot be converted from 'Float64' to 'Int'def total(a: Int, b: Int) -> Int: ^hello.mojo:4:5: note: candidate not viable: value passed to 'a' cannot be converted from 'Int' to 'Float64'def total(a: Float64, b: Float64) -> Float64: ^mojo: error: failed to parse the provided Mojo source moduleThere’s an Int and a Float64 version, but nothing for one of each. Mojo won’t quietly turn an Int variable into a Float64. Write total(Float64(x), y) to use the Float64 version.
Ambiguous calls
Section titled “Ambiguous calls”Sometimes two versions fit equally well, and Mojo refuses to guess:
def show(x: Int8): print("Int8:", x)
def show(x: Int64): print("Int64:", x)
def main(): show(1)hello.mojo:8:5: error: ambiguous call to 'show', each candidate requires 1 implicit conversion, disambiguate with an explicit cast show(1) ^~~~hello.mojo:1:5: note: candidate declared heredef show(x: Int8): ^hello.mojo:4:5: note: candidate declared heredef show(x: Int64): ^mojo: error: failed to parse the provided Mojo source moduleThe literal 1 can become an Int8 or an Int64 with the same effort, so neither wins. The error tells you the fix, an explicit cast:
def show(x: Int8): print("Int8:", x)
def show(x: Int64): print("Int64:", x)
def main(): show(Int8(1)) var n: Int64 = 5 show(n)Output:
Int8: 1Int64: 5A variable that already has one of the types (n is an Int64) matches exactly, so there’s nothing to decide.
Overloads and default values don’t mix well
Section titled “Overloads and default values don’t mix well”Default values can make two versions match the same call. Here, greet("Ana") fits both:
def greet(name: String): print("Hi", name)
def greet(name: String, greeting: String = "Hi"): print(greeting, name)
def main(): greet("Ana")hello.mojo:8:5: error: ambiguous call to 'greet' greet("Ana") ^~~~~hello.mojo:1:5: note: candidate declared heredef greet(name: String): ^hello.mojo:4:5: note: candidate declared heredef greet(name: String, greeting: String = "Hi"): ^mojo: error: failed to parse the provided Mojo source modulePick one approach: either one function with a default value, or two overloads without defaults. Here, the single function with greeting: String = "Hi" is all you need.
The return type isn’t enough
Section titled “The return type isn’t enough”Two versions that take the same arguments and differ only in what they return can’t exist side by side. Mojo picks a version from the call, and the call looks the same for both:
def parse(s: String) -> Int: return 0
def parse(s: String) -> Float64: return 0.0
def main(): print(parse("1"))hello.mojo:4:5: error: redefinition of function 'parse', cannot overload on return typedef parse(s: String) -> Float64: ^hello.mojo:1:5: note: previous definition heredef parse(s: String) -> Int: ^mojo: error: failed to parse the provided Mojo source moduleGive them different names instead, like parse_int and parse_float. The same goes for raises: two functions that differ only in whether they raise count as the same signature. The function overload reference lists every rule Mojo uses to choose.
Fixed versus variadic
Section titled “Fixed versus variadic”A version with a fixed list of arguments beats a variadic one (*args) when both fit:
def take(x: Int): print("one Int")
def take(*xs: Int): print("many Ints:", len(xs))
def main(): take(1) take(1, 2, 3)Output:
one Intmany Ints: 3take(1) fits both, and Mojo prefers the exact one. take(1, 2, 3) only fits the variadic version.
When to overload
Section titled “When to overload”Overloading is a good fit when every version does the same job on a different kind of input, like describe or double above. You’ll see it all over the standard library: String(...) and Int(...) accept many different kinds of values because their constructors are overloaded.
It’s a bad fit when the versions do different things. Two functions called save where one writes a file and the other sends an email will confuse every reader. Use different names.
And if you’re writing the same body over and over for many types, that’s what generics are for: one function that works with any type meeting some rule. You’ll get there in Mojo Generics. The Mojo manual’s section on overloaded functions shows how the two fit together.
Coming from Python?
Section titled “Coming from Python?”| Python | Mojo | |
|---|---|---|
Two defs with the same name |
The second replaces the first | Both exist; Mojo picks one per call |
| One function, many types | Check with isinstance, or functools.singledispatch |
Write one overload per type, or use generics |
| When the choice happens | At runtime | When the program is built |
| Different return type only | Not applicable | Error: “cannot overload on return type” |
Practice
Section titled “Practice”1. Area of different shapes
Section titled “1. Area of different shapes”Write two overloads of area: one that takes a single side: Float64 (a square) and one that takes width: Float64, height: Float64 (a rectangle). Print area(3.0) and area(3.0, 4.0).
Hint: the overloads differ only in how many arguments they take.
Show solution
def area(side: Float64) -> Float64: return side * side
def area(width: Float64, height: Float64) -> Float64: return width * height
def main(): print(area(3.0)) print(area(3.0, 4.0))Output:
9.012.0Mojo picks the version by counting the arguments in each call.
2. Shout anything
Section titled “2. Shout anything”Write shout with two overloads: one takes a String and prints it in upper case with ! at the end; the other takes an Int and prints the number followed by !!!. Call both.
Hint: String has an .upper() method.
Show solution
def shout(text: String): print(text.upper() + "!")
def shout(n: Int): print(String(n) + "!!!")
def main(): shout("hello") shout(42)Output:
HELLO!42!!!"hello" matches the String version and 42 matches the Int version. String(n) turns the number into text so it can be joined with +.
3. Fix the ambiguity
Section titled “3. Fix the ambiguity”This program doesn’t build. Without removing either function, make it print small: 7.
def report(x: Int8): print("small:", x)
def report(x: Int32): print("medium:", x)
def main(): report(7)Hint: the literal 7 fits both types equally well.
Show solution
def report(x: Int8): print("small:", x)
def report(x: Int32): print("medium:", x)
def main(): report(Int8(7))Output:
small: 7Int8(7) is already an Int8, so it matches the first version exactly and the call isn’t ambiguous anymore.
- Overloading means several functions with the same name but different argument types or counts.
- Mojo picks the version when the program is built, by looking at the arguments only.
- Literals go to their natural type:
1toInt,1.0toFloat64. - If two versions fit equally, the call is ambiguous; fix it with an explicit conversion like
Int8(1). - You can’t overload on the return type (or on
raises) alone. - Avoid overloads whose default values make them match the same call.
Next up: closures, functions defined inside other functions that can use the variables around them.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Overloaded functions (Mojo manual): the official introduction to overloads and overload resolution.
- Function overload reference: every rule Mojo uses to pick a version, with edge cases.
- Function declarations reference: what counts as a function’s signature.
- Parameterization (Mojo manual): compile-time parameters, the step toward writing one generic function instead of many overloads.