Menu
Coddy logo textTech

Return Values

Part of the Fundamentals section of Coddy's Rust journey — lesson 51 of 75.

The return statement in a method is used to specify the value or values that the method should produce as its output. For example, the following method will output 100:

fn function_name() -> i32 {
	return 100;
}

Notice that the function is returning an i32 type of data because of the arrow -> sign.

To pass the return value to a variable, write:

let number: i32 = function_name();

Now the number variable will hold 100 because this is what the method returned.

Note that the return type of the method (i32 in this case) must match the data type of the variable where you're storing the returned value.

challenge icon

Challenge

Easy

Each test case has three inputs.

The first input indicates how many times to do iterations, and the last two inputs are numbers that we will do operations on.

Create a method that receives two arguments and returns the bigger number of the two. if both are equal then return one of them.

Iterate iterations times and for each iteration do:

  • Call the method with num1, num2, and save the result in a variable.
  • Divide the bigger number of the two by 2, and then replace the original larger variable with the new result value.
  • print the new value.  
  • Continue doing it until the program iterated iterations times or one of the numbers is smaller than 2.

Note you already have the skeleton of the code!

Cheat sheet

The return statement specifies the value a function produces as output:

fn function_name() -> i32 {
    return 100;
}

Use the arrow -> to specify the return type. Store the returned value in a variable:

let number: i32 = function_name();

The return type must match the variable's data type where you store the returned value.

Try it yourself

use std::io;

fn bigger(arg1: f64, arg2: f64) -> f64 {
    // Complete the function

}

fn main() {
    let mut input_iter = String::new();
    let mut input_num1 = String::new();
    let mut input_num2 = String::new();

    io::stdin().read_line(&mut input_iter).unwrap();
    io::stdin().read_line(&mut input_num1).unwrap();
    io::stdin().read_line(&mut input_num2).unwrap();

    let iter: i32 = input_iter.trim().parse().unwrap();
    let mut num1: f64 = input_num1.trim().parse().unwrap();
    let mut num2: f64 = input_num2.trim().parse().unwrap();

    for _ in 0..iter {
        // Write your code below
    }
}
quiz iconTest yourself

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

All lessons in Fundamentals