结构体中枚举的生命周期参数

Del*_*ore 5 enums struct lifetime rust

我不明白为什么这种类型的结构会出现错误

enum Cell <'a> {
    Str(&'a str),
    Double(&'a f32),
}

struct MyCellRep<'a> {
    value: &'a Cell,
    ptr: *const u8,
}

impl MyCellRep{
    fn new_from_str(s: &str) {
        MyCellRep { value: Cell::Str(&s), ptr: new_sCell(CString::new(&s)) }
    }

    fn new_from_double(d: &f32) {
        MyCellRep { value: Cell::Double(&d), ptr: new_dCell(&d) }
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误

14:22 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
src\lib.rs:14     value : & 'a Cell ,
Run Code Online (Sandbox Code Playgroud)

所以我也尝试过

struct MyCellRep<'a> {
    value: &'a Cell + 'a,
    ptr: *const u8,
}
Run Code Online (Sandbox Code Playgroud)

但得到了

14:22 error: expected a path on the left-hand side of `+`, not `&'a Cell`
Run Code Online (Sandbox Code Playgroud)

我认为Cell应该有 的生命周期MyCellRep,并且Cell::Str至少Cell::Double应该有 的生命周期Cell

最终我能做的就是说

let x = MyCellRef::new_from_str("foo");
let y = MyCellRef::new_from_double(123.0);
Run Code Online (Sandbox Code Playgroud)

更新 我想添加,通过更改单元格定义,代码的其余部分也应该更改为以下内容,以便其他人搜索答案。

pub enum Cell<'a> {
    Str(&'a str),
    Double(&'a f32),
}


struct MyCellRep<'a> {
    value: Cell<'a>, // Ref to enum 
    ptr: *const u8, // Pointer to c struct
}

impl<'a>  MyCellRep<'a> {
    fn from_str(s: &'a str) -> DbaxCell<'a> {
        MyCellRep { value: Cell::Str(&s) , ptr: unsafe { new_sCell(CString::new(s).unwrap()) } }
    }

    fn from_double(d: &'a f32) -> DbaxCell {
        MyCellRep{ value: Cell::Double(&d) , ptr: unsafe { new_dCell(*d) } }
    }
}
Run Code Online (Sandbox Code Playgroud)

我喜欢 Rust 的地方就像 OCaml 一样,如果它能编译就可以工作:)

mdu*_*dup 5

您(可以理解)误解了错误消息:

14:22 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
src\lib.rs:14     value : & 'a Cell ,
Run Code Online (Sandbox Code Playgroud)

您认为“但是我提供了生命周期参数!确实如此'a!” 但是,编译器试图告诉您,您没有Cell 提供生命周期参数(而不是对它的引用):

Cell<'a>
Run Code Online (Sandbox Code Playgroud)