[英]Lifetime parameters for an enum within a struct
我不明白为什么我这种结构会出错
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>
mdup是正确的 ,但错误消息可以帮助您 。 出于某种原因,许多人忽略了指向错误的错误消息部分:
<anon>:7:16: 7:20 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
<anon>:7 value: &'a Cell,
^~~~
有时,我想提交一个PR,使^~~~~
在终端^ _ ^中闪烁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.