rust/tests/ui/manual_flatten.rs

99 lines
2.4 KiB
Rust
Raw Normal View History

2021-01-28 18:38:34 -06:00
#![warn(clippy::manual_flatten)]
2021-03-24 10:15:15 -05:00
#![allow(clippy::useless_vec)]
2021-01-28 18:38:34 -06:00
fn main() {
2021-02-02 12:04:20 -06:00
// Test for loop over implicitly adjusted `Iterator` with `if let` expression
2021-01-28 18:38:34 -06:00
let x = vec![Some(1), Some(2), Some(3)];
for n in x {
if let Some(y) = n {
println!("{}", y);
2021-01-28 18:38:34 -06:00
}
}
2021-02-02 12:04:20 -06:00
// Test for loop over implicitly implicitly adjusted `Iterator` with `if let` statement
2021-01-28 18:38:34 -06:00
let y: Vec<Result<i32, i32>> = vec![];
for n in y.clone() {
2021-02-02 12:04:20 -06:00
if let Ok(n) = n {
println!("{}", n);
};
}
// Test for loop over by reference
for n in &y {
2021-01-28 18:38:34 -06:00
if let Ok(n) = n {
println!("{}", n);
}
}
// Test for loop over an implicit reference
// Note: if `clippy::manual_flatten` is made autofixable, this case will
// lead to a follow-up lint `clippy::into_iter_on_ref`
let z = &y;
for n in z {
if let Ok(n) = n {
println!("{}", n);
}
}
2021-02-02 12:04:20 -06:00
// Test for loop over `Iterator` with `if let` expression
2021-01-28 18:38:34 -06:00
let z = vec![Some(1), Some(2), Some(3)];
let z = z.iter();
for n in z {
if let Some(m) = n {
println!("{}", m);
2021-01-28 18:38:34 -06:00
}
}
// Using the `None` variant should not trigger the lint
// Note: for an autofixable suggestion, the binding in the for loop has to take the
// name of the binding in the `if let`
2021-01-28 18:38:34 -06:00
let z = vec![Some(1), Some(2), Some(3)];
for n in z {
if n.is_none() {
println!("Nada.");
}
}
// Using the `Err` variant should not trigger the lint
for n in y.clone() {
if let Err(e) = n {
println!("Oops: {}!", e);
}
}
// Having an else clause should not trigger the lint
for n in y.clone() {
if let Ok(n) = n {
println!("{}", n);
} else {
println!("Oops!");
}
}
2021-03-24 10:15:15 -05:00
let vec_of_ref = vec![&Some(1)];
for n in &vec_of_ref {
if let Some(n) = n {
println!("{:?}", n);
}
}
let vec_of_ref = &vec_of_ref;
for n in vec_of_ref {
if let Some(n) = n {
println!("{:?}", n);
}
}
let slice_of_ref = &[&Some(1)];
for n in slice_of_ref {
if let Some(n) = n {
println!("{:?}", n);
}
}
2021-01-28 18:38:34 -06:00
// Using manual flatten should not trigger the lint
for n in vec![Some(1), Some(2), Some(3)].iter().flatten() {
println!("{}", n);
}
}