Program successfully runs, but i'm not sure why


#1

I’ve been working through the recommended exercises in the beta version of the Rust book. After completing one of them last night, I awoke this morning to the realization that i’m not sure how my program passed the borrow checker. Here is the relevant snippet of code:

[CODE]
fn main() {

let mut v = vec![0];
    let (num, freq) = mode(&v);

println!("The average is {:?}.", average(&v));
println!("The median is {:?}.", median(&mut v));

if freq > 1 {
  println!("The mode is {:?}, which occurs {:?} times.", num, freq);

} else {
println!(“There is no mode”);
}
}
[/CODE]

According to my understanding of the reference rules i’m only allowed to have just one mutable reference or any number of immutable references, but not both. I don’t understand how the above code isn’t an example of having both and thus shouldn’t run.


#2

Since your references to v are passed to functions that don’t return references based on their input parameters, the references only exist for the time of the function call.

The rule is that you can have one mutable borrow or many immutable borrows at the same time, not ever.


#3

It depends on your fn mode, but assuming its return type doesn’t contain any lifetimes tying it back to &v, then that shared borrow ends as soon as mode returns. The borrows for your average and median are scoped only to those println expressions regardless, since nothing binds the return value any longer.


#4

Thanks for the clarification.