0

I had been learning Rust recently.

I stumbled across the following code:

pub fn to_bytes(values: &[u32]) -> Vec<u8> {
    for &(mut value) in values {
        //...
    }
}

I do not understand the & in the for loop. What exactly is happening here?

I figured out that if you iterate over a vector, using a for loop, you get a reference (found here):

let v = vec![1, 2, 3];
for value in &v {
    // value is a reference 
}

Then why do I need another & in the first snipped?

Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
Donut
  • 197
  • 9

1 Answers1

3

I figured out that if you iterate over a vector, using a for loop, you get a reference.

This is actually not true. It depends on your vector. If your vector is a reference, it yields a reference. Otherwise it yields an owned value.

Back to your first question:

pub fn to_bytes(values: &[u32]) -> Vec<u8> {
    for &(mut value) in values {
        // value will be of type u32
        //...
    }
}

This is called destructuring. Since values here is of type &[u32], the value it yields with the for loop is of type &u32. With the help of &, you dereference the pointer so the value variable here will be of type u32.

Alternatively you can also do the following, but your value will be of type &u32.

pub fn to_bytes(values: &[u32]) -> Vec<u8> {
    for mut value in values {
        // value will be of type &u32
        //...
    }
}
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • First of all: Thanks about you statement regarding the yielding of reference/value. :) Regarding the actual answer: It am trying to understand it but I feel it is not so easy. You are saying, that with the help of `&`, I am dereferencing the pointer. I thought that `*` is used for dereferencing (the link says it too). Am I missing something? – Donut Feb 04 '20 at 16:23
  • Oh wait: The value which is yielded by the iterator is pattern matched against `mut value`. The `&` is used to destructure the value. I hope that is correct o.O – Donut Feb 04 '20 at 16:47
  • 1
    Yes. That's correct. * is used in front of the value while & is used in front of the variable . – Psidom Feb 04 '20 at 17:06
  • Ok cool. Now I get it. Thanks :) – Donut Feb 04 '20 at 17:40
  • Please look for duplicate questions and answers before answering. – Shepmaster Feb 04 '20 at 18:25