I think in this case my reference needs to be mutable because I'm sorting the array, and it needs to be a reference because I want to use the same vector to calculate the mean and mode. I have tried various combinations of mut
in the function signature and variable declaration but have not been able to get this to compile (including the suggestion in the error message but probably incorrectly implemented).
I'm trying to implement a simple median function (I am aware there's probably a built in way but am doing this as an exercise)
fn main() {
let mut v = vec![1, 2, 3, 4, 5, 5, 4, 3];
println!("{}", median(&v));
}
fn median(mut vec: &Vec<i32>) -> usize {
vec.sort();
let len: usize = vec.len();
let middle = len as i32 / 2;
println!("{}", &middle);
0
}
This gives the following error
error[E0596]: cannot borrow `*vec` as mutable, as it is behind a `&` reference
--> src/main.rs:7:5
|
6 | fn median(mut vec: &Vec<i32>) -> usize {
| --------- help: consider changing this to be a mutable reference: `&mut std::vec::Vec<i32>`
7 | vec.sort();
| ^^^ `vec` is a `&` reference, so the data it refers to cannot be borrowed as mutable