1

I am working through The Rust Book and I am having problems with the following:

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_finds_median_for_even_number_of_elements() {
        let mut v: Vec<i32> = vec![1, 3];
        assert_eq!(*median(&mut v).unwrap(), 2);
    }
}

fn median<'a>(v: &'a mut Vec<i32>) -> Option<&'a i32> {
    v.sort();
    let midpoint = v.len() / 2;
    match midpoint % 2 == 0 {
        true => Some(&(v[midpoint] - v[midpoint - 1] / 2)),
        false => v.get(midpoint),
    }
}

When I build this I get the following:

error[E0515]: cannot return value referencing temporary value
  --> src/lib.rs:16:17
   |
16 |         true => Some(&(v[midpoint] - v[midpoint - 1] / 2)),
   |                 ^^^^^^-----------------------------------^
   |                 |     |
   |                 |     temporary value created here
   |                 returns a value referencing data owned by the current function

How do I convert the i32 value from v[midpoint] - v[midpoint - 1] / 2 to a reference which the caller can access?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Mike Harris
  • 869
  • 9
  • 21
  • 1
    You cannot. For an `i32`, I'd recommend just dereferencing the value if it's present, but you can also use a `Cow` in other cases. – Shepmaster Jan 15 '19 at 01:39
  • 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) – Shepmaster Jan 15 '19 at 01:51
  • 1
    The duplicates [applied to your question](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=db10a2afe154b0002515783c610c12a6), plus a healthy smattering of logic bugs fixed. – Shepmaster Jan 15 '19 at 01:59

0 Answers0