pub const fn likely(b: bool) -> bool
🔬This is a nightly-only experimental API. (
likely_unlikely
)Expand description
Hints to the compiler that a branch condition is likely to be true. Returns the value passed to it.
It can be used with if
or boolean match
expressions.
When used outside of a branch condition, it may still influence a nearby branch, but probably will not have any effect.
It can also be applied to parts of expressions, such as likely(a) && unlikely(b)
, or to
compound expressions, such as likely(a && b)
. When applied to compound expressions, it has
the following effect:
likely(!a) => !unlikely(a)
likely(a && b) => likely(a) && likely(b)
likely(a || b) => a || likely(b)
See also the function cold_path()
which may be more appropriate for idiomatic Rust code.
§Examples
#![feature(likely_unlikely)]
use core::hint::likely;
fn foo(x: i32) {
if likely(x > 0) {
println!("this branch is likely to be taken");
} else {
println!("this branch is unlikely to be taken");
}
match likely(x > 0) {
true => println!("this branch is likely to be taken"),
false => println!("this branch is unlikely to be taken"),
}
// Use outside of a branch condition may still influence a nearby branch
let cond = likely(x != 0);
if cond {
println!("this branch is likely to be taken");
}
}