【发布时间】:2015-06-11 16:04:54
【问题描述】:
我不明白为什么这种结构会出错
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,如果它编译它就可以工作:)
【问题讨论】:
标签: struct enums rust lifetime