I think I understand, at a very high level what the difference between &
and *
in Rust is as it pertains to memory management.
What is the difference between the following code snippets. Are there dangers to applying one approach versus the other?
for (i, item) in bytes.iter().enumerate() {
if *item == b' ' {
return i;
}
}
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
for (i, item) in bytes.iter().enumerate() {
if item == &b' ' {
return i;
}
}
As I understand it, when I return a value from iter()
I am returning a reference to the element found in bytes
. If I want to make a comparison on the item, I need to either compare between two references &u8
or I need to make &item
a reference itself so that when I call item
it is of type u8
, or I need to dereference item
when I compare it so that item
= &u8
-> *item
= u8
.
When I run the code using
(i, &item)
, when I callitem
later on, is this exactly the same thing as dereferencing in the second example, or is there a fundamental difference about how the compiler is interpreting the first code snippet and the second code snippet?Is there anything wrong with the third code snippet? I realize this is a bit of an opinion based question. I realize that if I were to assign a value to another variable using
item
(or*item
, or assigning the value as a reference) I would have different datatypes being returned later on. Aside from managing your data types, is there anything else to keep in mind when considering ifitem == &b' '
is the right tool for the job?