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?