Rust By Example: For Loops and Range

Опубликовано: 20 Декабрь 2024
на канале: Stephen Blum
103
5

If you're coding in Rust or similar languages, you usually use a for loop. This is a way to go over a group of items or 'iterate'. There are other loops too, like while loops, or infinite loops that stop with a break statement.

But for loops are common when you know how many items you're working with. Imagine the for loop as jumping into a pool of items. For example, the range statement lets you make a list, like from 1 to 100 (it says 101, but the last object isn't included).

Just remember, it starts at zero. For loops work well with an iterator, like a tool that changes a list into something you can iterate over. It starts with the first element and doesn't include the last element.

So if you run the program, you'll see it starts with 1 and ends with 100. An iterator is like a tool making the lists more convenient. You can call up three types of iterators: the into iter, iter, and iter mute.

They basically do the same job: going through your group of items, but in a different way. The catch with into iter is that you can use the data during the loop, but it's then gone forever. When you're sure you're done with the list and want it locked away, you can use this.

The cloned iterator makes a copy of the data. Though this uses more memory and makes your computer work harder, it's useful when you don't want the data touched at all. And finally, the iter mute lets you read and edit the data through a borrow, so you can keep the data around.

This is probably the most normal way to code. This gives read and write access to the data. You're not stuck with read-only.

You can now change the list and use it again later. You can even protect yourself by building rust's tools into your plans. But when you want extra security, and don't need the write access, you can stick with the standard iterator.

So these are ways to adjust your code, but bear in mind it changes how the computer uses memory and how hard it works. The goal here is to tailor the code to perform well and keep the application safe.