mark_unlikely

Function mark_unlikely 

Source
pub const fn mark_unlikely()
Expand description

Marks a code block as cold, indicating to the compiler that it is unlikely to be called. This can help the compiler optimize for the common case.

This function does not take any arguments and does not return any value. It is primarily used to mark functions or code paths that are rarely executed, such as error handling or panic paths. Example: marking the None variant of an Option as unlikely.

In many hot paths an Option<T> is expected to be Some.
By marking the None arm using mark_unlikely we give the optimizer a hint that this branch is rarely taken.

use branches::{mark_unlikely};

#[derive(Debug)]
enum Status {
    Ok(i32),
    Err(String),
}

fn get_value(status: Status) -> i32 {
    match status {
        Status::Ok(v) => v,
        // The error case is rare, hint the compiler accordingly.
        Status::Err(err) => {
            mark_unlikely();
            eprintln!("unexpected error: {:?}", err);
            -1
        }
    }
}