Differences in timing and timing

Why does this work

#[derive(Debug)]
pub struct Foo<'a,'b> {
    s : &'a str,
    n : &'b i32
}
#[test]
fn test_struct() {
    let f = Foo { s : &"bar" , n : &17 };
    println!("{:?}",f);
}

      

But it is not

#[derive(Debug)]
pub enum Bar<'a,'b> {
    Baz ( &'a str),
    Fub ( &'b i32)
}
#[test]
fn test_struct() {
    let b = Bar::Baz(&"Foo");
    let c = Bar::Fub(&17);
    println!("{:?} {:?}",b,c);
}

      

Error (part of a larger file, so ignore line numbers)

src\lib.rs:176:27: 176:29 error: borrowed value does not live long enough
src\lib.rs:176         let c = Bar::Fub(&17);
                       ^~~~~~~~~~~~~~~~~~~~~~

      

It seems to me that let c = Bar::Fub(&17)

, 17 has the same lifespan as the previous line where it "Foo"

is created on the stack. If I change it a little and do

let h = &17;
let c = Bar::Fub(&h);

      

In this case, it's pretty clear that h lasts longer than Bar :: Fub (). So I'm not sure how I can get this to work.

This is a continuation of the Lifetime parameters for enumeration inside a struct

+3


source to share


1 answer


It seems to me that let c = Bar :: Fub (& 17), 17 last the same lifetime as the previous line where "Foo" is created on the stack

A string literal always has a lifetime 'static

and will therefore always live long enough.

I think the problem is that you are clicking on that the enum expression is actually a function call. In a sense, this means that the lifetime of the argument is ignored when calculating the lifetime of the Enum. The Enum's lifetime appears to be a little longer, as if you had written:

let c: Bar;
let x = &17;
c = Bar::Fub(x);

      

which is already covered in Address Scaling: Doesn't Live Long enough



In this case, it is completely clear that h lasts longer than Bar :: Fub ().

Yes, the lifespan is clear here, and it works in Playpen :

let x = &17;
let c = Bar::Fub(x);

      

so I'm not sure what you are asking.

+2


source







All Articles