Lifetime parameters for an enum within a struct

7.5k views Asked by At

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 :)

2

There are 2 answers

2
mdup On BEST ANSWER

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 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):

Cell<'a>
3
Shepmaster On

mdup is correct, but the error message helps you. For some reason, many people ignore the part of the error message that points to 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 submit a PR that makes the ^~~~~ blink in the terminal ^_^.