How to Write Early Returns in Rust

Use the return keyword inside a function to exit immediately and skip remaining code.

Use the return keyword inside a function to exit immediately and return a value, skipping any remaining code in that function. This is often used in conditional logic to handle edge cases or early success/failure states.

fn check_value(x: i32) -> Option<i32> {
    if x < 0 {
        return None; // Early return if x is negative
    }
    
    if x == 0 {
        return Some(0); // Early return for zero
    }
    
    Some(x * 2) // Default return if no early return triggered
}