@@ -10,43 +10,41 @@ use rustc_span::{sym, Span};
10
10
use rustc_trait_selection:: traits:: TraitEngineExt ;
11
11
12
12
declare_lint ! {
13
- /// ### What it does
14
- ///
15
13
/// Checks for `for` loops over `Option` or `Result` values.
16
14
///
17
- /// ### Why is this bad?
18
- /// Readability. This is more clearly expressed as an `if
19
- /// let`.
15
+ /// ### Explanation
16
+ ///
17
+ /// Both `Option` and `Result` implement `IntoIterator` trait, which allows using them in a `for` loop.
18
+ /// `for` loop over `Option` or `Result` will iterate either 0 (if the value is `None`/`Err(_)`)
19
+ /// or 1 time (if the value is `Some(_)`/`Ok(_)`). This is not very useful and is more clearly expressed
20
+ /// via `if let`.
21
+ ///
22
+ /// `for` loop can also be accidentally written with the intention to call a function multiple times,
23
+ /// while the function returns `Some(_)`, in these cases `while let` loop should be used instead.
24
+ ///
25
+ /// The "intended" use of `IntoIterator` implementations for `Option` and `Result` is passing them to
26
+ /// generic code that expects something implementing `IntoIterator`. For example using `.chain(option)`
27
+ /// to optionally add a value to an iterator.
20
28
///
21
29
/// ### Example
22
30
///
23
31
/// ```rust
24
32
/// # let opt = Some(1);
25
33
/// # let res: Result<i32, std::io::Error> = Ok(1);
26
- /// for x in opt {
27
- /// // ..
28
- /// }
29
- ///
30
- /// for x in &res {
31
- /// // ..
32
- /// }
33
- ///
34
- /// for x in res.iter() {
35
- /// // ..
36
- /// }
34
+ /// # let recv = || Some(1);
35
+ /// for x in opt { /* ... */}
36
+ /// for x in res { /* ... */ }
37
+ /// for x in recv() { /* ... */ }
37
38
/// ```
38
39
///
39
40
/// Use instead:
40
41
/// ```rust
41
42
/// # let opt = Some(1);
42
43
/// # let res: Result<i32, std::io::Error> = Ok(1);
43
- /// if let Some(x) = opt {
44
- /// // ..
45
- /// }
46
- ///
47
- /// if let Ok(x) = res {
48
- /// // ..
49
- /// }
44
+ /// # let recv = || Some(1);
45
+ /// if let Some(x) = opt { /* ... */}
46
+ /// if let Ok(x) = res { /* ... */ }
47
+ /// while let Some(x) = recv() { /* ... */ }
50
48
/// ```
51
49
pub FOR_LOOP_OVER_FALLIBLES ,
52
50
Warn ,
0 commit comments