Multiple Return Values
Part of the Fundamentals section of Coddy's Rust journey — lesson 52 of 75.
In Rust, a function can return multiple values by using a tuple as the return type. A tuple is a group of different values bundled into one unit.
For example:
fn get_coordinates() -> (i32, i32) {
let x = 10;
let y = 20;
(x, y) // Return a tuple
}And this is how to call the function:
let (x, y) = get_coordinates();
// Destructure the tuple
// into separate variables
println!("{}, {}", x, y);You can return as many values as you need by adding more elements to the tuple. For example:
fn get_details() -> (String, i32, f64) {
let name = String::from("Alice");
let age = 30;
let score = 95.5;
(name, age, score)
// Return a tuple with three values
}And this is how to call the function:
let (name, age, score) = get_details();
println!("{}, {}, {}", name, age, score);Challenge
EasyCreate a function named get_user_info that returns a tuple containing a user's name, age, and email address. The function should have the following signature:
fn get_user_info() -> (String, i32, String)Inside the function, create the following variables:
name: aStringinitialized to "Bob"age: ani32initialized to 25email: aStringinitialized to "bob@example.com"
Return these three values as a tuple.
In the main function, call get_user_info and destructure the returned tuple into separate variables named name, age, and email. Then, print these values to the console using println! in the following format:
Name: [name], Age: [age], Email: [email]Cheat sheet
Functions can return multiple values using tuples as the return type:
fn get_coordinates() -> (i32, i32) {
let x = 10;
let y = 20;
(x, y) // Return a tuple
}Call the function and destructure the tuple into separate variables:
let (x, y) = get_coordinates();
println!("{}, {}", x, y);You can return multiple values of different types:
fn get_details() -> (String, i32, f64) {
let name = String::from("Alice");
let age = 30;
let score = 95.5;
(name, age, score)
}let (name, age, score) = get_details();
println!("{}, {}, {}", name, age, score);Try it yourself
fn get_user_info() -> (String, i32, String) {
// Create name, age, and email variables here
// Return the tuple
}
fn main() {
// Call get_user_info and destructure the returned tuple
// Print the values
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 311Functions
Declaring FunctionsParameters and ArgumentsReturn ValuesMultiple Return ValuesRecap - Sigma FunctionRecap - Validation Function3Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input