Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way to write a for loop without using the iterator value?

Tags:

rust

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?

like image 300
Cole Reynolds Avatar asked Apr 29 '15 00:04

Cole Reynolds


People also ask

How can we use for loop when the number of iterations are not known?

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.

What are the types of objects allowed for iteration in for loop?

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.

How do you iterate without a loop in Python?

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.

What does the i mean in for loops?

"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".


1 Answers

You can write _ as your pattern, meaning “discard the value”:

let mut x: i32 = 0; for _ in 1..10 {     x += 1; } 
like image 123
Chris Morgan Avatar answered Oct 02 '22 17:10

Chris Morgan