[英]Does Rust narrow lifetimes to satisfy constraints defined on them?
Please consider this example ( playground ):请考虑这个例子( 操场):
struct Container<'short, 'long: 'short, T: 'long> {
short_prop: &'short u8,
long_prop: &'long T,
}
fn main() {
let value = 9;
let long = &value;
{
let short = &value;
let res = Container {
short_prop: long,
long_prop: short, // why is this not an error?
};
println!("{} {}", res.short_prop, res.long_prop);
}
}
In Container
I specify 'long: 'short
which I'm assuming means that 'long
should live at least as long as 'short
.在
Container
我指定'long: 'short
我假设这意味着'long
应该至少与'short
一样长。 In main
, the variable long
should live longer than short
because it has a bigger scope.在
main
中,变量long
的寿命应该比short
长,因为它的 scope 更大。
So Container
expects whatever goes into long_prop
to live at least as long as whatever goes into short_prop
.因此,
Container
期望long_prop
中的任何内容至少与short_prop
中的内容一样长。 Yet the compiler is perfectly happy with me passing the longer-lived long
into short_prop
and the shorter-lived short
into long_prop
.然而,编译器对我将寿命较长的
long
传递给short_prop
并将寿命较短的short
传递给long_prop
感到非常满意。
Is this because at the instantiation of Container
the compiler narrows the lifetime of long
to be equal to the lifetime of short
thus satisfying the 'long: 'short
constraint (since equality of lifetimes is fine)?这是因为在
Container
的实例化时,编译器将long
的生命周期缩小到等于short
的生命周期,从而满足'long: 'short
约束(因为生命周期的相等性很好)? Or is there another reason?还是另有原因?
Is this because at the instantiation of
Container
the compiler narrows the lifetime of'long
to be equal to the lifetime of'short
thus satisfying the'long: 'short
constraint (since equality of lifetimes is fine)?这是因为在
Container
的实例化时,编译器将'long
的生命周期缩小为等于'short
的生命周期,从而满足'long: 'short
约束(因为生命周期的相等性很好)?
Yes.是的。
Or is there another reason?
还是另有原因?
Nope.没有。
Here's an example with a simpler Container
struct which only holds 1 reference at a time.这是一个更简单的
Container
结构的示例,它一次只包含 1 个引用。 The reason it can hold both long
and short
references is because longer lifetimes are subtypes of shorter ones, but the overall lifetime of the container
variable is narrowed to the minimum overlap of both of these lifetimes, which means container
goes out of scope the same time as short
does:它可以同时持有
long
引用和short
引用的原因是因为较长的生命周期是较短生命周期的子类型,但是container
变量的整体生命周期缩小到这两个生命周期的最小重叠,这意味着container
同时退出 scope short
:
#[derive(Debug)]
struct Container<'a> {
some_ref: &'a str
}
fn main() {
let long = String::from("long");
let long_ref = &long;
let mut container = Container {
some_ref: long_ref,
};
dbg!(&container);
{
let short = String::from("short");
let short_ref = &short;
container.some_ref = short_ref;
dbg!(&container);
} // both short & container go out of scope here
dbg!(&container); // error, container dropped in block above, has same lifetime as short
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.