This question already has an answer here:
Compiler asking for lifetime in struct when lifetime is given

(1个答案)


1年前关闭。




我无法弄清楚为get_best_slide的返回类型指定生存期的正确方法,而Enum恰好是best_h。该枚举保留对best_vlongest之一的引用。

看起来很像official doc中的Enum函数示例,除了返回类型是&'a Option<Slide>

pub enum Image {
    Horizontal { image_id: usize },
    Vertical { image_id: usize },
}

pub enum Slide<'a> {
    H { h: &'a Image },
    V { v: &'a Image, other_v: &'a Image },
}

fn get_best_slide<'a>(
    best_score_h: usize,
    best_h: Option<&'a Image>,
    best_score_v: usize,
    best_v: Option<(&'a Image, &'a Image)>,
) -> &'a Option<Slide> {
    match (best_h, best_v) {
        (None, None) => None,
        (Some(h), None) => Some(Slide::H { h }),
        (None, Some((v0, v1))) => Some(Slide::V { v: v0, other_v: v1 }),
        (Some(h), Some((v0, v1))) => {
            if best_score_h >= best_score_v {
                Some(Slide::H { h })
            } else {
                Some(Slide::V { v: v0, other_v: v1 })
            }
        }
    }
}

编译器不满意:
error[E0106]: missing lifetime specifier
  --> src/main.rs:16:17
   |
16 | ) -> &'a Option<Slide> {
   |                 ^^^^^ expected lifetime parameter
   |
   = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `best_h` or `best_v`

也许我指定的生命周期参数不在正确的位置?
  • Option<&'a Slide>看起来不正确
  • 我也尝试过ojit_code(编译器提示都一样)
  • 最佳答案

    它需要Slide的生命周期参数,您需要显式设置它

     -> Option<Slide<'a>>
    

    区别是:
  • &'a Option<Slide>表示我将在整个生命周期内借用Option<Slide>'a
  • Option<Slide<'a>>意味着我将在生存期Slide中创建'a,以便内部操作可以显式使用此生存期。
  • 关于enums - 将枚举的生存期指定为返回类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55941560/

    10-12 03:28