0

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Sven Harris
  • 2,884
  • 1
  • 10
  • 20
  • `median(&mut v)` and `fn median(vec: &mut Vec)` – Shepmaster Apr 02 '19 at 19:26
  • 1
    **Please** save yourself some heartache and take the time to read the official book: [*The Rust Programming Language*](https://doc.rust-lang.org/book/). It's online and free to read. It has an entire chapter discussing references, including [a section on mutable references](https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references). – Shepmaster Apr 02 '19 at 19:28
  • See also [Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?](https://stackoverflow.com/q/40006219/155423) — since you don't need to add/remove items from the `Vec`, you can take `&mut [i32]` instead. – Shepmaster Apr 02 '19 at 19:32
  • @Shepmaster in fact the book is exactly what I'm working through at the moment, I have clearly misunderstood some of the concepts so will go back and read that chapter again, thanks! – Sven Harris Apr 03 '19 at 05:49

0 Answers0