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

标签 struct enums rust lifetime

我不明白为什么我在使用这种类型的结构时会出错

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) }
    }
}

我得到了错误

14:22 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
src\lib.rs:14     value : & 'a Cell ,

所以我也试过了

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

但是得到了

14:22 error: expected a path on the left-hand side of `+`, not `&'a Cell`

我假设 Cell 应该有 MyCellRep 的生命周期,Cell::StrCell::Double 至少应该有 Cell 的生命周期。

最终我能做的就是说

let x = MyCellRef::new_from_str("foo");
let y = MyCellRef::new_from_double(123.0);

更新 我想补充一点,通过更改 Cell 定义,其余代码也应更改为以下内容,以供其他人搜索答案。

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) } }
    }
}

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

最佳答案

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

14:22 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
src\lib.rs:14     value : & 'a Cell ,

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

Cell<'a>

关于struct - 结构中枚举的生命周期参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30785915/

相关文章:

c - 为指向 C 中记录的指针中的键赋值

c - 将结构指针传递给函数不会修改引用

c++ - 无法获取存储在 vector 结构中的信息

c# - Unity 在向 OWIN 添加 Active Directory 访问权限时尝试实例化枚举参数

rust - 用 Rust 解析二进制协议(protocol)的最佳方法是什么

C fwrite() - 结构与 fwrite() 分开 - 结构项目不匹配

mysql - 按所有枚举值分组而不指定枚举值

java - 我可以使用 Spring 注入(inject)来注入(inject)枚举吗?

string - 为什么我来自BufReader::lines的行不匹配?

rust - 为什么我的 Rust 代码无法加载 tera 模板?