Here is an example where the if then else cases do the same thing but cannot be collapsed into one case:
fn max_index<T : PartialOrd>( v : &[T] ) -> usize {
let mut imax = v.len();
for (i, v_i) in v.iter().enumerate() {
if imax == v.len() {
imax = i;
} else if v[imax] < *v_i {
imax = i;
}
}
imax
}
fn main() {
let v = vec![0, 1, 2, 3];
let imax = max_index(&v);
println!( "max = {}", v[imax] );
}
1 Like
You can just use or, because rust short circuits. If the first condition is true, the second one will not get evaluated.
if imax == v.len() || v[imax] < *v_i {
imax = i;
}
2 Likes
Another option (feel free not to use this if array indexing is more clear to you) is
if v.get(imax).is_none_or(|v_imax| v_imax < v_i) {
imax = i;
}
This seems theoretically preferable to me, since it's more type-safe.
MOCKBA
January 21, 2026, 5:08am
4
Indeed, Clippy finds tons of such problems in my code, so I always have the solution pointed by [quote="consistent-milk12, post:2, topic:137686"]
You can just use or
[/quote]
in my pocket.