简体   繁体   English

结构与枚举的生命周期差异

[英]Struct vs enum lifetime differences

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 this doesn't 但事实并非如此

#[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);
}

The error is (part of a bigger 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);
                       ^~~~~~~~~~~~~~~~~~~~~~

To me it seems like let c = Bar::Fub(&17) , the 17 lasts the same life time as the previous line where "Foo" is created on the stack. 对我而言,似乎let c = Bar::Fub(&17) ,17持续与前一行相同的生命周期,其中在堆栈上创建"Foo" If I modify it slightly and do 如果我稍微修改它并做

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

In which case it's completely clear that h lasts longer than Bar::Fub(). 在这种情况下,完全清楚h持续时间长于Bar :: Fub()。 SoI'm not sure how I can can get this to work. 所以我不知道如何才能让它发挥作用。

This is a follow up to Lifetime parameters for an enum within a struct 这是结构中枚举的Lifetime参数的后续

To me it seems like let c = Bar::Fub(&17), the 17 lasts the same life time as the previous line where "Foo" is created on the stack 对我来说,似乎让c = Bar :: Fub(&17),17持续与前一行相同的生命周期,其中“Foo”在堆栈上创建

A string literal always has 'static lifetime and will therefor always live long enough. 字符串文字总是具有'static生命周期,因此总是活得足够长。

I think the issue is that you are hitting is the fact that an enum expression is actually somewhat of aa function call. 我认为问题在于你所遇到的事实是枚举表达式实际上是一个函数调用。 Somewhat meaning that the lifetime of the argument is ignored in the computation of the Enum's lifetime. 有点意思是在计算Enum的生命周期时忽略参数的生命周期。 The Enum's lifetime apparently is marginally larger, as if you wrote: Enum的一生显然略大,就好像你写道:

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

which is already addressed in Scope of addresses: Does not live long enough 已经在地址范围内解决了:活得不够久

In which case it's completely clear that h lasts longer than Bar::Fub(). 在这种情况下,完全清楚h持续时间长于Bar :: Fub()。

Yes, the lifetimes are clear here, and it works in the Playpen : 是的,这里的生命周期很清楚,它适用于婴儿围栏

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

so I'm not sure what you are asking. 所以我不确定你在问什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM