#[SOLVED] Trait bounds with lifetimes (PhantomData)

6 messages · Page 1 of 1 (latest)

brisk mist
#

How would I add a lifetime parameter to a struct that has trait bounds that have lifetimes?

My code so far:

#[derive(Debug)]
pub struct Parameter<'src, T> where T: NonTerminal<'src> + Terminal<'src> {
    pub data: T,
    pub comma: Spanned<()>,
    ph: PhantomData<T>
}
error[E0392]: parameter `'src` is never used
  --> src/ast/mod.rs:76:22
   |
76 | pub struct Parameter<'src, T> where T: NonTerminal<'src> + Terminal<'src> {
   |                      ^^^^ unused parameter
   |
   = help: consider removing `'src`, referring to it in a field, or using a marker such as `std::marker::PhantomData`
#

Ok just thought of a silly idea... but it works!

pub struct Parameter<'src, T>
where
    T: NonTerminal<'src> + Terminal<'src>,
{
    pub data: T,
    pub comma: Spanned<()>,
    dummy: &'src str,
    // ph: PhantomData<T>,
}
brisk mist
#

Also thought of this:

pub struct Parameter<'src, T>
where
    T: NonTerminal<'src> + Terminal<'src>,
{
    pub data: T,
    pub comma: Spanned<()>,
    phantom: &'src PhantomData<T>,
}

But it does come at a cost still :/

struct Spooky<T> {
    phantom: PhantomData<T>
}

struct SpookRef<'src, T> {
    phantom_ref: &'src PhantomData<T>
}

fn bob() {
    let spooky = Spooky { phantom: PhantomData::<()> }; // let spooky: Spooky<()> // size = 0, align = 0x1
    let spooky_ref = SpookRef {phantom_ref: &PhantomData::<()>}; // let spooky_ref: SpookRef<'_, ()> // size = 8, align = 0x8
}
marsh socket
#

put the reference inside the PhantomData so you don't have to create it:

    phantom: PhantomData<&'src T>,

or if they're unrelated:

    phantom: PhantomData<(T, &'src ())>,
brisk mist
#

oh thanks!

#

no solved tag ferrisThink