简体   繁体   中英

What are the different ways to return a value from a function in Rust?

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. 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM