我不明白为什么我在使用这种类型的结构时会出错
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::Str
和 Cell::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/