我看过多个帖子,例如this或this,但我认为这不重复。我想我还不太明白如何使用寿命比彼此更长寿。这是一个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 | | }
| |_________^
我完全迷失了如何解释它。
答案 0 :(得分:2)
您需要明确指定两个参数的生命周期,使它们相同:
impl<'a> Line<'a> {
pub fn new(start: &'a Point, end: &'a Point) -> Self {
Line {
start: start,
end: end,
}
}
}
否则编译器无法决定为输出选择哪个输入生命周期。我推荐相关的Rust Book section on lifetime elision,尤其是以下3条规则:
- 函数参数中的每个省略生命周期变为不同的生命周期 参数。
如果只有一个输入生命周期,无论是否已经过去,那就是生命周期 被赋予所有退出生命周期的返回值 功能
如果有多个输入生命周期,但其中一个是&amp; self或 &amp; mut self,self的生命周期分配给所有省略的输出 寿命。
否则,忽略输出生命周期是错误的。