'Why are these two code samples equal? Difference between references, borrowed variables, pointers
fn largest(num_list: &[i32]) -> i32 {
let mut largest = num_list[0];
for &num in num_list {
if num > largest {
largest = num
}
}
largest
}
fn largest2(num_list: &[i32]) -> i32 {
let mut largest = num_list[0];
for num in num_list {
if num > &largest {
largest = *num
}
}
largest
}
fn main() {
let num_list = vec![30, 20, 10, 60, 50, 40];
let largest = largest(&num_list);
let largest2 = largest2(&num_list);
println!("The largest number in num_list fn is: {}.", largest);
println!("The largest number in num_list fn is: {}.", largest2);
}
As you can see there are some slight differences in largest and largest2. Can someone help me understand the differences here and why both samples of code actually function the same?
Solution 1:[1]
The main difference between the two samples stems from your loop statement, for num in num_list vs for &num in num_list. First of all, it is important to understand that they are equivalent to for [...] in num_list.iter(), that is, they iterate over references of elements of num_list. These references, of type &i32, are then assigned to either num or &num. In the first case, we just have a direct assignment, therefore num: &i32. In the second case, there is an irrefutable assignment that binds num to the number, therefore num: i32. Incidentally, this is possible because, even though you are trying to move out a value from a borrow, i32: Copy, so Rust compiles it fine.
The rest is just adaptation: either you are using a &i32, or directly a i32. For instance, when num: &i32, and you want to compare it with largest, you should dereference num and then compare it, giving *num > largest. However, num > &largest works too because Rust knows how to compare two &i32, by dereferencing both (so it will actually produce *num > largest). Similarly, when you assign to largest, you must assign an i32, so you dereference num: largest = *num.
It's easy to understand, then, why these two pieces of code do the same thing: in one version, you copy the value of a pointer to an integer in num, and then use it, whereas in the other you keep the dereference in num, and simply dereference it each time you need to use it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
