Devolver varios valores
Devuelva tuplas desde una función.
Devolver varios valores es una lección gratuita de Mojo Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Mojo Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Mojo Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
More Than One Result
Sometimes a function naturally produces two answers at once. In Mojo you can hand them all back together using a tuple.
Returning a Tuple
List the values separated by commas in the return. Mojo packs them into one tuple that the caller can take apart.
fn min_max(a: Int, b: Int) -> (Int, Int):
if a < b:
return (a, b)
return (b, a)Declaring the Tuple Type
The arrow type spells out each slot. Here (Int, Int) tells readers and the compiler exactly what comes back.
fn split() -> (String, Int): ...Unpacking the Result
The caller can unpack the tuple into separate names in one line, giving each value a clear identity right away.
lo, hi = min_max(8, 3)
print(lo) # 3Names Match Order
Unpacking follows position. The first name takes the first value, the second name the second, so the order must line up with the return.
low, high = min_max(8, 3)Or Keep the Whole Tuple
You do not have to unpack. Hold the tuple in one variable and reach into it by index when you need a piece.
pair = min_max(8, 3)
print(pair[0]) # 3Why Not Just One Return?
Bundling related results keeps them together. Returning both a value and its status in one tuple is cleaner than scattering them across globals.
fn parse() -> (Int, Bool): ... # value and successTuples Can Mix Types
A tuple is not limited to one type. You can return a String and an Int side by side, each keeping its own type.
fn user() -> (String, Int):
return ("Ada", 36)Reading Multi-Value Returns
When you see an arrow leading to parentheses, expect several results. The signature is your map for how to unpack them.
Keep Tuples Small and Clear
Two or three values in a tuple read well. If you need many, a named struct usually communicates intent better than a long tuple.
A Common Pattern
Returning a result plus an error or flag is a classic use of tuples. The caller unpacks both and reacts to each in turn.
value, ok = try_parse(text)Quick Check
How does a Mojo function hand back more than one value at once?
Recap: Bundle and Unpack
Return several results as a tuple, declare its type in the signature, then unpack by position. Keep tuples small or reach for a struct.
Preguntas frecuentes
¿La lección «Devolver varios valores» es gratis?
Sí — el texto completo de «Devolver varios valores» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Mojo Academy, actualiza a CoddyKit PRO. El curso de Mojo Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Devolver varios valores»?
Devuelva tuplas desde una función. Practicas Mojo Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Mojo Academy?
No se requiere experiencia previa. Mojo Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Devolver varios valores»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Mojo Academy?
Sí. Cada lección de Mojo Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Argumentos posicionales y de palabra clave
- Valores de argumentos predeterminados
- Devolver varios valores
- Leer firmas de funciones