I don't understand why I get an error with this type of structure
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) }
}
}
I get the error
14:22 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
src\lib.rs:14 value : & 'a Cell ,
So I tried also
struct MyCellRep<'a> {
value: &'a Cell + 'a,
ptr: *const u8,
}
but got
14:22 error: expected a path on the left-hand side of `+`, not `&'a Cell`
I presume the Cell
should have the lifetime of MyCellRep
, and Cell::Str
and Cell::Double
should at least have the lifetime of the Cell
.
Eventually what I was to be able to do is just say
let x = MyCellRef::new_from_str("foo");
let y = MyCellRef::new_from_double(123.0);
Update I would like to add, by changing the Cell definition, the rest of the code should also change to the following for anyone else searching answers.
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) } }
}
}
What I love about Rust is just like OCaml, if it compiles it works :)
You (understandably) misinterpreted the error message:
You thought "But I provided the lifetime parameter! It is
'a
!" However, the compiler is trying to tell you that you did not provide a lifetime parameter for Cell (not the reference to it):