Lifetime parameters for enumeration in structure
I don't understand why I am getting 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 am getting 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 and
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 suppose I Cell
should have a lifetime MyCellRep
, Cell::Str
and Cell::Double
should at least have a lifetime Cell
.
In the end what I had to do was 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 definition of the cell, the rest of the code should also change to the following for anyone else looking for 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 the same as OCaml, if it compiles it works :)
source to share
You (understandably) misinterpreted the error message:
14:22 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
src\lib.rs:14 value : & 'a Cell ,
You thought, "But I presented a lifespan parameter! This 'a
!" However, the compiler is trying to tell you that you did not specify a lifetime parameter for Cell (and not a reference to it):
Cell<'a>
source to share
mdup is correct , but the error message will help you . For some reason, many people ignore the portion of the error message indicating the error:
<anon>:7:16: 7:20 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
<anon>:7 value: &'a Cell,
^~~~
Sometimes, I want to present a PR that makes the ^~~~~
terminal blink ^ _ ^.
source to share