Member-only story

Working with iterators in Rust — A brief Introduction

Shanmukh Sista
4 min readNov 7, 2022

In this short tutorial, we’ll look at Iterators in Rust, and how to work with for loops using iterators — both mutably and immutably. Iterators, like the name implies, allow us to loop through list list likedata structures in rust. It can be a Vector, a Hashmap, or even a custom type that can implement Iterator traits.

Since we are working with Vectors or references in general ( which are stored on heap ), we would have to follow rules for references even when dealing with primitive types such as integers and floats. Let’s take two simple examples to understand this.

Setup a new Project

For this tutorial, we’ll create a new rust Project as a library.

cargo new --lib map-iterator-demo

Let’s add the following code to src/lib.rs file .This is the starting point of our library.

We’ll create a new vector with 10 elements and create a new iterator for the list.

mod iterators_demo {
pub fn multiply( ){
// define a vector of 10 integers.
let nums = vec![1,2,3,4,5,6,7,8,9,10];
// create an iterator to iterate over this list.
let nums_iterator =nums.iter();
}
}

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response