1

I came across following two ways:

#[derive(Debug)]
struct InputList(i32, i32, i32, i32);
#[derive(Debug)]
struct OutputList(i32, i32, i32, i32);

// Option 1
fn foo(input_list: InputList) -> OutputList {
    return OutputList(input_list.0, input_list.1, input_list.2, input_list.3);
}

// Option 2
fn bar(input_list: InputList) -> OutputList {
    OutputList(input_list.0, input_list.1, input_list.2, input_list.3)
}

fn main() {
    let input_list1 = InputList(1, 2, 3, 4);
    let input_list2 = InputList(6, 7, 8, 9);

    println!("foo() invocation output: {:?}", foo(input_list1));
    println!("bar() invocation output: {:?}", bar(input_list2));
}

Are these the only two options?

1 Answer 1

8
  1. Have an expression without a semicolon in the tail position of the function.

    fn implicit() -> i32 {
        1
    }
    

    See also:

  2. Use a return statement.

    fn explicit() -> i32 {
        return 1;
    }
    

    See also:


    Macros can contain return statements inside of them, so you might not always see the return.

    macro_rules! thing {
        ($val:expr) => {{
            if $val {
                return 42;
            }
        }};
    }
    
    fn macro() -> i32 {
        thing!(true);
        99
    }
    

    See also:

  3. Use ? in a function that returns a type implementing Try.

    fn error() -> Option<i32> {
        None?;
        Some(42)
    }
    

    See also:

Other cases

Depending on exactly how you categorize "returning from a function", these might also apply:

  1. Use .await in an asynchronous function.

    async fn sometime() -> i32 {
        async { 42 }.await;
        99
    }
    

    This one is tricky and non-obvious because the compiler rewrites the function to contain a state machine and implement the Future trait. Every .await can return a Poll::Pending, but the caller of the function never has to think about this.

    See also:

  2. Panicking.

    fn bail_out() -> Option<i32> {
        panic!()
    }
    

    Here, the function "returns", but you generally don't get a value.

    See also:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.