[英]How to analyze generic lifetime when it is relevant to variance
0 // code snippet 1 1 2 struct MutStr<'a >{ 3 s: &'a mut &'a str, 4 } 5 6 fn main() { 7 let mut s: &'static str = "hello"; 8 *MutStr{ 9 s: &mut s, 10 }.s = "world"; 11 println!("{}", s); 12 }
I have read this article, knowing some basic concepts about variance, such as covariance invariance and contravariance.
<\/blockquote>我读过这篇文章,了解了一些关于方差的基本概念,例如协方差不变性和逆变性。 And I kind of think my question relate to that, but don't know how to use that to analyze code snippet 1.
而且我有点认为我的问题与此有关,但不知道如何使用它来分析代码片段 1。
You are on the right track, the difference does lie with lifetime variance.您走在正确的轨道上,差异确实在于终生差异。 There is a table in the Rust Reference 10.5 Subtyping and Variance<\/a> that I think is helpful:
Rust Reference 10.5 Subtyping and Variance<\/a>中有一张我认为很有帮助的表格:
Type 类型<\/th>
Variance in 'a<\/code>
'a<\/code>方差
<\/th>
Variance in T<\/code>
T<\/code>的方差
<\/th><\/tr><\/thead>
&'a T<\/code><\/td>
covariant 协变<\/td>
covariant 协变<\/td><\/tr>
&'a mut T<\/code><\/td>
covariant 协变<\/td>
invariant 不变的<\/td><\/tr><\/tbody><\/table>
In your second snippet, your references are immutable meaning the lifetime associated with them can be shortened as necessary.
在您的第二个片段中,您的引用是不可变的,这意味着可以根据需要缩短与它们相关的生命周期。 A reference to the variable
y<\/code> cannot lengthen its lifetime so the reference to
x<\/code> must be shortened.
对变量
y<\/code>的引用不能延长其生命周期,因此必须缩短对
x<\/code>的引用。
An thus the reference bound to
r<\/code> is tied to the lifetime of
y<\/code> and therefore you get an error when you try to use
r<\/code> after
y<\/code> has gone out of scope.
因此,绑定到
r<\/code>的引用与
y<\/code>的生命周期相关联,因此在
y<\/code>超出范围后尝试使用
r<\/code>时会出现错误。
In the first snippet however, you have a mutable reference to a
&'a str<\/code> .
然而,在第一个片段中,您有一个对
&'a str<\/code>的可变引用。
If you look at the table above, you'll see that types referenced by a mutable reference are invariant and since the type is itself a
&'a str<\/code> , that means that
'a<\/code> is invariant.
如果您查看上表,您会发现可变引用所引用的类型是不变的,并且由于该类型本身是
&'a str<\/code> ,这意味着
'a<\/code>是不变的。
This means, unlike in the second snippet, the compiler can not<\/em> shorten the lifetime of
'a<\/code> at all.
这意味着,与第二个片段不同,编译器根本无法<\/em>缩短
'a<\/code>的生命周期。
So when you try to use
s<\/code> to make a
MutStr<\/code> , the compiler sees that you're passing a
&'static str<\/code> that it cannot shorten, so
'a<\/code> must be
'static<\/code> .
因此,当您尝试使用
s<\/code>制作
MutStr<\/code>时,编译器会看到您正在传递一个无法缩短的
&'static str<\/code> ,因此
'a<\/code>必须是
'static<\/code> 。
But then it tries to reconcile that
'a<\/code> is also linked to the variable
s<\/code> which is not
'static<\/code> , so you get the error.
但随后它试图调和
'a<\/code>也链接到不是
'static<\/code>的变量
s<\/code> ,所以你得到了错误。
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.