41 lines
1.0 KiB
Plaintext
41 lines
1.0 KiB
Plaintext
|
|
== Why is this an issue?
|
|
Looping over `x.next()` is misleading and can introduce subtle bugs. `x.next()` returns an `Option` which should be handled properly. When used in a loop, `Option` implements `IntoIterator`, resulting in unexpected behavior where only a single element or `None` might be processed, leading to difficult-to-diagnose errors.
|
|
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
[source,rust,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
for value in iterator.next() {
|
|
// Noncompliant: Looping directly over `iterator.next()`
|
|
println!("{value}");
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,rust,diff-id=1,diff-type=compliant]
|
|
----
|
|
for value in iterator {
|
|
// Compliant: Looping directly over `iterator`
|
|
println!("{value}");
|
|
}
|
|
----
|
|
|
|
Alternatively, handling the Option:
|
|
|
|
[source,rust,diff-id=1,diff-type=compliant]
|
|
----
|
|
if let Some(value) = iterator.next() {
|
|
// Process the single value
|
|
println!("{value}");
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#iter_next_loop
|