Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create 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: a String initialized to "Bob"
  • age: an i32 initialized to 25
  • email: a String initialized 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
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals