References and Iteration
There’s a slight possibility that what I’ve written here may not be 100% correct. In such case I’ll come back and update my stance as I learn more about the language.
As a Rust noob, yesterday I came to know about the “pattern” of iteration. It’s like the combination of having two things: rust passing you the references of values and how to use them, and how the values are owned/copied/moved in all of this. There was a good enough discussion that I had on #rust-beginners where the community was really helpful.
So iteration is done using
for keyword, and while some data types provide
iteration out of the box, I was mostly looking at iterating BTreeMap or HashMap,
let’s call them containers.
Iterating a container also depends on whether it contains a value which
Copy or not.
Copy is a trait, which if implemented by a type
allows the type to move by copying its value instead of copying the references
clone() . Most of the primitives like
f32, etc implement
it. Other types like
Vec<T> do not, and that’s why we cannot
move their borrowed copies. A more detailed discussion is available at StackOverflow
To do this iteration, rust provides a pattern:
v are actually references to the keys and values of the
hashmap, and are used as such, so these have the types
In case I write the following:
v inside the
for expression become the values,
instead of becoming the references. Rust pattern matches and removes the
reference operator before passing the values inside the
for. The values
now have the types
This matters in case
Copy or not. In case they do,
then nothing bad happens (like i32). In case they don’t (eg. Vec,
HashMap<T1, T2>), then
v in the first snippet is actually
&HashMap<T1, T2> inside the
for expression, and
Vec<T> in the second
one. So usage depends on what we are doing.
For example, here’s an iteration of
& inside the iterator doesn’t matter because both
Copy and the compiler copies these.
In case the type does not implement
Copy like a
it becomes important how we use the references with iterators.
Author Tushar Tyagi
LastMod Jun 19, 2018