【问题标题】:Cannot infer an appropriate lifetime when building a struct with multiple references with the same lifetime构建具有相同生命周期的多个引用的结构时无法推断出适当的生命周期
【发布时间】:2017-06-23 18:12:49
【问题描述】:

我看过多个帖子,例如 thisthis,但我认为这不是重复的。我想我还不太明白如何利用生命来延长彼此的寿命。这是一个 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 | |         }
   | |_________^

我完全不知道如何解释它。

【问题讨论】:

    标签: rust


    【解决方案1】:

    您需要明确指定两个参数的生命周期,以便它们相同:

    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条规则:

    • 函数参数中每个省略的生命周期都变成了不同的生命周期 参数。
    • 如果只有一个输入生命周期,无论是否省略,该生命周期 被分配给返回值中的所有省略的生命周期 功能。

    • 如果有多个输入生命周期,但其中之一是 &self 或 &mut self,将self的生命周期分配给所有省略的输出 一生。

    否则,省略输出生命周期是错误的。

    【讨论】:

    • 哦,有道理。我想我必须在一生和借阅中再读一遍。
    猜你喜欢
    • 2021-03-23
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多