Getting started with Rust (coming from some experience with C++ and Python), sorry for the noob question. Just got this piece of code running, but cannot figure why this is running.
fn get_largest(list: &[i32]) -> &i32 {
// Why return a reference to i32?
let mut largest = &list[0]; // If largest is a reference to list[0], will it modify list[0]
for item in list {
# Why item is assigned as an &i32 here?
if item > largest {
largest = item;
}
}
largest // How is the reference valid after largest is popped from the stack
}
fn main() {
let number_list:Vec<i32> = vec![102, 34, 6000, 89, 54, 2, 43, 8];
let result:&i32 = get_largest(&number_list);
println!("The largest number is {result}");
for item in number_list {
# Why item is assigned as an i32 here?
println!("{item}")
} // This to prove the array stays the same.
}
Basically, the questions are as highlighted in the comments.
- It seems
largest
is a reference to the zero-th element of the array. So iflargest
is a mutable reference, does not it modify the array's zero-th element itself? - Finally,
largest
seems to be a local reference inside theget_largest
function. As soon as the function returns, should not the reference to a local variable be void as the local variable is popped from the stack?