如何返回对i32的引用的Option?

时间:2019-01-15 01:32:14

标签: rust borrowing

我正在研究Rust Book,并且在以下方面遇到了问题:

#[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),
    }
}

构建此文件时,我得到以下信息:

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

如何将i32值从v[midpoint] - v[midpoint - 1] / 2转换为调用者可以访问的引用?

0 个答案:

没有答案