Skip to main content

return

Keyword return 

Source
Expand description

Returns a value from a function.

A return marks the end of an execution path in a function:

fn foo() -> i32 {
    return 3;
}
assert_eq!(foo(), 3);

return is not needed when the returned value is the last expression in the function. In this case the ; is omitted:

fn foo() -> i32 {
    3
}
assert_eq!(foo(), 3);

return returns from the function immediately (an “early return”):

fn main() -> Result<(), &'static str> {
   let contents = "Hello, world!";

   if contents.contains("impossible!") {
       return Err("oh no!");
   }

   if contents.len() > 9000 {
       return Err("over 9000!");
   }

   Ok(())
}

Within closures and async blocks, return returns a value from within the closure or async block, not from the parent function:

fn foo() -> i32 {
    let closure = || {
        return 5;
    };

    let future = async {
        return 10;
    };

    return 15;
}

assert_eq!(foo(), 15);