Mojo Return Values
A return value is what a function hands back to the code that called it. You’ve already used -> Int and return. This lesson goes a bit further: returning early, returning several values at once, returning a list (which needs one extra character), and a Mojo-only way to write the result called a named result.
One value, one type
Section titled “One value, one type”The return type after -> is a promise, and return keeps it. The value you return is converted to that type when Mojo knows how, so a literal 1 can come back as a Float64, and "Hello" as a String:
def get_greeting() -> String: return "Hello"
def half_of(n: Int) -> Float64: return Float64(n) / 2.0
def one() -> Float64: return 1
def main(): print(get_greeting()) print(half_of(7)) print(one())Output:
Hello3.51.0What Mojo won’t do is guess. return "no" from a function that promises an Int fails with “cannot implicitly convert ‘StringLiteral[“no”]’ value to ‘Int’“.
Returning early
Section titled “Returning early”return ends the function on the spot. That makes it easy to handle simple cases first and keep the rest of the code flat:
def grade(score: Int) -> String: if score >= 90: return "A" if score >= 80: return "B" if score >= 70: return "C" return "F"
def main(): print(grade(95), grade(85), grade(72), grade(40))Output:
A B C FEach if returns as soon as it matches, so there’s no need for elif or else. The last return "F" covers everything left, which also satisfies Mojo’s rule that every path must return a value.
A return inside a loop stops the loop too. This function gives back the first negative number it finds:
def first_negative(values: List[Int]) -> Int: for v in values: if v < 0: return v return 0
def main(): var a: List[Int] = [3, -2, -7] var b: List[Int] = [1, 2, 3] print(first_negative(a)) print(first_negative(b))Output:
-20Returning 0 for “not found” is a bit of a cheat, since 0 could be a real answer in other cases. The proper tool for “maybe a value” is Optional, which you’ll meet in Mojo Optional.
Returning several values with a tuple
Section titled “Returning several values with a tuple”A function can only return one thing. But that one thing can be a tuple: a small, fixed group of values. You write the type as Tuple[...] with the type of each item, and return the values in parentheses:
def min_max(values: List[Int]) -> Tuple[Int, Int]: var lo = values[0] var hi = values[0] for v in values: if v < lo: lo = v if v > hi: hi = v return (lo, hi)
def main(): var nums: List[Int] = [4, 9, 1, 7] var result = min_max(nums) print(result) print(result[0], result[1])Output:
(1, 9)1 9You can read each part by position, result[0] and result[1]. Usually it’s nicer to unpack the tuple straight into named variables, the way you would in Python:
def divide(a: Int, b: Int) -> Tuple[Int, Int]: return (a // b, a % b)
def main(): var quotient, remainder = divide(17, 5) print("17 / 5 =", quotient, "remainder", remainder)Output:
17 / 5 = 3 remainder 2The items don’t have to share a type:
def user_info() -> Tuple[String, Int, Bool]: return ("Ana", 30, True)
def main(): var name, age, active = user_info() print(name, age, active) var status, _, _ = user_info() print(status)Output:
Ana 30 TrueAnaUse _ for a part you don’t need. The number of names on the left has to match the tuple, or Mojo stops with “cannot declare ‘a’ without a contextual type from its initializer”.
Tuples have their own lesson, Mojo Tuples. If you find yourself returning three or four values that belong together, a small struct with named fields is usually clearer. You’ll see those in Mojo Structs.
Returning a list needs ^
Section titled “Returning a list needs ^”This one catches almost everyone. Build a list in a function, return it, and Mojo complains:
def numbers() -> List[Int]: var xs: List[Int] = [1, 2, 3] xs.append(4) return xs
def main(): print(numbers())hello.mojo:4:12: error: value of type 'List[Int]' cannot be implicitly copied, it does not conform to 'ImplicitlyCopyable' return xs ^~hello.mojo:4:12: note: consider transferring the value with '^' return xs ^ ^hello.mojo:4:12: note: you can copy it explicitly with '.copy()' return xs ^ .copy()mojo: error: failed to parse the provided Mojo source moduleA list can hold a lot of data, so Mojo never copies one without being asked. The first note gives the fix: add ^ after the name. It means “hand this value over, I’m done with it”:
def numbers() -> List[Int]: var xs: List[Int] = [1, 2, 3] xs.append(4) return xs^
def main(): var result = numbers() result.append(5) print(result)Output:
[1, 2, 3, 4, 5]Nothing gets copied: the list moves out of the function and into result. Simple values like Int, Float64, Bool and String don’t need the ^. Lists, dictionaries and most bigger types do. The ^ operator gets its own lesson, Mojo Moving Values.
Named results with out
Section titled “Named results with out”Mojo has a second way to write a return value: declare it as an argument marked out. It’s a variable that starts out empty, and the function’s job is to fill it in. Whatever it holds at the end is what the caller gets:
def make_label(n: Int, out label: String): label = "Item #" label += String(n)
def squares(n: Int, out result: List[Int]): result = List[Int]() for i in range(1, n + 1): result.append(i * i)
def main(): print(make_label(7)) print(squares(4))Output:
Item #7[1, 4, 9, 16]A few things to notice:
- The caller doesn’t pass the
outargument.make_label(7)looks exactly like a call to a function declared-> String. - There’s no
returnneeded. When the function ends, the value oflabelgoes back to the caller. squaresdoesn’t need^, because the list is built right where the result lives.- The function must set it. If some path leaves it empty, Mojo reports “use of uninitialized value”.
A function can still have only one result, either -> Type or one out argument. By convention the out argument goes last.
Coming from Python?
Section titled “Coming from Python?”| Python | Mojo | |
|---|---|---|
| Return several values | return a, b |
return (a, b) with -> Tuple[A, B] |
| Tuple type | tuple[int, int] |
Tuple[Int, Int] |
| Unpack the result | q, r = f() |
var q, r = f() |
| Return a list you built | return xs |
return xs^ |
No return at the end |
Returns None |
Error, unless the result is an out argument |
Practice
Section titled “Practice”1. Celsius and Fahrenheit
Section titled “1. Celsius and Fahrenheit”Write convert(celsius: Float64) -> Tuple[Float64, Float64] that returns the same temperature in Fahrenheit and in Kelvin. Unpack the result for 25.0 and print both.
Hint: Fahrenheit is c * 9.0 / 5.0 + 32.0, Kelvin is c + 273.15.
Show solution
def convert(celsius: Float64) -> Tuple[Float64, Float64]: return (celsius * 9.0 / 5.0 + 32.0, celsius + 273.15)
def main(): var f, k = convert(25.0) print("Fahrenheit:", f) print("Kelvin:", k)Output:
Fahrenheit: 77.0Kelvin: 298.15The function returns one tuple with two Float64 values, and var f, k = ... unpacks it into two variables.
2. Keep the big ones
Section titled “2. Keep the big ones”Write big_numbers(values: List[Int], limit: Int) -> List[Int] that returns a new list with only the values greater than limit. Print the result for [5, 12, 8, 20] with a limit of 9.
Hint: build the new list in a var, then return it with ^.
Show solution
def big_numbers(values: List[Int], limit: Int) -> List[Int]: var result = List[Int]() for v in values: if v > limit: result.append(v) return result^
def main(): var nums: List[Int] = [5, 12, 8, 20] print(big_numbers(nums, 9))Output:
[12, 20]Without the ^ you’d get the “cannot be implicitly copied” error. The ^ moves the finished list out to the caller.
3. Same thing with out
Section titled “3. Same thing with out”Rewrite big_numbers from exercise 2 so it uses a named result out result: List[Int] instead of -> List[Int].
Hint: the caller doesn’t change at all. Inside, start with result = List[Int]().
Show solution
def big_numbers(values: List[Int], limit: Int, out result: List[Int]): result = List[Int]() for v in values: if v > limit: result.append(v)
def main(): var nums: List[Int] = [5, 12, 8, 20] print(big_numbers(nums, 9))Output:
[12, 20]No return and no ^: the list is filled in place and handed back when the function ends.
- The value after
returnmust fit the return type; literals convert automatically. returnends the function right away, even inside a loop.- Return several values as a tuple:
-> Tuple[Int, Int]andreturn (a, b). - Unpack a tuple with
var a, b = f(); use_for parts you don’t need. - Returning a list you built needs
return xs^, because Mojo won’t copy it silently. - A named result (
out result: Type) is filled in by the function and returned withoutreturn.
Next up: scope, where a variable lives and where it stops existing.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Return values (Mojo manual): the official guide to
return, named results and returning references. - Tuple (std docs): everything a
Tuplecan do. - Ownership (Mojo manual): why lists move with
^instead of being copied. - Function declarations reference: return types and
outarguments in the exact grammar.