Assuming I want a finite loop using a range:
let mut x: i32 = 0; for i in 1..10 { x += 1; }
The compiler will spit out the warning:
warning: unused variable: `i`, #[warn(unused_variables)] on by default for i in 1..10 { ^
Is there a more idiomatic way to write this that won't make the compiler complain?
If the number of iterations is not known up front, then this is a case where a for loop can't be used. The while loop is quite simple. It contains no indices or defined variables, so it is convenient when a loop is simply needed to keep performing an action until a desired condition is (or isn't) met.
These include the string, list, tuple, dict, set, and frozenset types. But these are by no means the only types that you can iterate over. Many objects that are built into Python or defined in modules are designed to be iterable.
Looping without a for loopGet an iterator from the given iterable. Repeatedly get the next item from the iterator. Execute the body of the for loop if we successfully got the next item. Stop our loop if we got a StopIteration exception while getting the next item.
"i" is a temporary variable used to store the integer value of the current position in the range of the for loop that only has scope within its for loop. You could use any other variable name in place of "i" such as "count" or "x" or "number".
You can write _
as your pattern, meaning “discard the value”:
let mut x: i32 = 0; for _ in 1..10 { x += 1; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With