Thursday, June 26, 2014

Rust Note 3: For loops in Rust

Rust is a very progressive language. It tries to not make the same mistake that D made, and include parts of the language just because its predecessors had them. One such removal is the for loop.

For the uninformed, a for loop syntax in most languages is as such: for(declaration; guard; statement). An example:

 for(int x = 0; x < 100;  x++){;} 

This for loop will do nothing 100 times. But, Rust doesn't have a for loop? How can you do an equal amount of nothing? The answer is to use the range() function of the standard library. Range() is an iterator, meaning that the rust version of the for loop can act over it. You can generate a list of numbers with range(lowerBounds, higherBounds) and iterate over it. Here's the translation of that loop from above:

for x in range (0, 100){ }

Splendid! You're doing nothing just as efficiently as in a traditional language. However, what if you want to do something other than increment x by one each time? Well, you're in luck. You could either
  • Implement the iterator trait for the type of data you're working on
  • Do it the lazy way
Lazy sounds easy, so here's how to get every third number in a for loop in rust.

let mut x: int = 0;
while x < 100{
  // Awesome stuff here
  x = x + 3

}

No comments:

Post a Comment