pub const fn unlikely(b: bool) -> bool
🔬This is a nightly-only experimental API. (
likely_unlikely
)Expand description
Hints to the compiler that a branch condition is unlikely 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 unlikely(a && b)
. When applied to compound expressions, it has
the following effect:
unlikely(!a) => !likely(a)
unlikely(a && b) => a && unlikely(b)
unlikely(a || b) => unlikely(a) || unlikely(b)
See also the function cold_path()
which may be more appropriate for idiomatic Rust code.
§Examples
#![feature(likely_unlikely)]
use core::hint::unlikely;
fn foo(x: i32) {
if unlikely(x > 0) {
println!("this branch is unlikely to be taken");
} else {
println!("this branch is likely to be taken");
}
match unlikely(x > 0) {
true => println!("this branch is unlikely to be taken"),
false => println!("this branch is likely to be taken"),
}
// Use outside of a branch condition may still influence a nearby branch
let cond = unlikely(x != 0);
if cond {
println!("this branch is likely to be taken");
}
}