![](/img/trans.png)
[英]cannot infer an appropriate lifetime for lifetime parameter with multiple references with the same lifetime inside a struct [E0495]
[英]Cannot infer an appropriate lifetime when building a struct with multiple references with the same lifetime
我已经看到了多篇文章像这样或这样 ,但我认为这是没有重复的。 我想我还不太了解如何使用寿命来使彼此寿命更长。 这是MWE:
struct Point;
pub struct Line<'a> {
pub start: &'a Point,
pub end: &'a Point,
}
impl<'a> Line<'a> {
pub fn new(start: &Point, end: &Point) -> Self {
Line {
start: start,
end: end,
}
}
}
fn main() {}
我收到错误消息
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src/main.rs:10:9
|
10 | Line {
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 9:51...
--> src/main.rs:9:52
|
9 | pub fn new(start: &Point, end: &Point) -> Self {
| ____________________________________________________^
10 | | Line {
11 | | start: start,
12 | | end: end,
13 | | }
14 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:12:18
|
12 | end: end,
| ^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the body at 9:51...
--> src/main.rs:9:52
|
9 | pub fn new(start: &Point, end: &Point) -> Self {
| ____________________________________________________^
10 | | Line {
11 | | start: start,
12 | | end: end,
13 | | }
14 | | }
| |_____^
note: ...so that expression is assignable (expected Line<'a>, found Line<'_>)
--> src/main.rs:10:9
|
10 | / Line {
11 | | start: start,
12 | | end: end,
13 | | }
| |_________^
我对如何解释它完全迷失了。
您需要明确指定两个参数的生存期,以使它们相同:
impl<'a> Line<'a> {
pub fn new(start: &'a Point, end: &'a Point) -> Self {
Line {
start: start,
end: end,
}
}
}
否则,编译器无法决定为输出选择哪个输入生存期。 我推荐有关寿命淘汰的Rust Book部分 ,尤其是以下3条规则:
- 函数参数中每个被忽略的生存期都变成一个不同的生存期参数。
如果恰好有一个输入生存期(是否已删除),则该寿命将分配给该函数的返回值中的所有已删除生存期。
如果有多个输入生存期,但其中一个是&self或&mut self,则将self的生存期分配给所有被忽略的输出生存期。
否则,延长输出寿命是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.