【问题标题】:Rust lifetime inference for struct methods结构方法的 Rust 生命周期推断
【发布时间】:2021-03-23 18:56:16
【问题描述】:

此代码基于 Rust 书中生命周期章节中的示例代码。我想知道相同方法的以下两个版本有何不同:

struct Important<'a> {
    part: &'a str,
}

impl<'a> Important<'a> {
    fn larger<'b>(&'b self, other: &'b str) -> &'b str {
        if self.part.len() > other.len() {
            self.part
        } else {
            other
        }
    }
}

struct Important<'a> {
    part: &'a str,
}

impl<'a> Important<'a> {
    fn larger(&self, other: &'a str) -> &str {
        if self.part.len() > other.len() {
            self.part
        } else {
            other
        }
    }
}

我猜在第一个版本中我们会指示编译器

  1. 找到一个生命周期 'b 使得 &amp;self 和引用 other 在此期间都有效(如果它们重叠,可能是两个生命周期中较短的那个)

  2. 确保返回的引用仅在该生命周期内使用'b,因为在外部它可能成为悬空引用。

第二版代码的作用是什么? Rust 书中的生命周期省略规则之一说,在结构方法中,返回的引用被分配了 &amp;self 参数的生命周期(这里是 'a),所以我们说 other 也应该是有效的与&amp;self 参数的生命周期相同,即'a 的生命周期?

从语义上讲,这是相同的代码还是这些版本的行为是否会因other 和结构的生命周期而有所不同?

【问题讨论】:

    标签: methods struct rust reference lifetime


    【解决方案1】:

    第二版代码的作用是什么? rust book 中的生命周期省略规则之一说,在 struct 方法中,返回的引用被分配了 &self 参数的生命周期(这里是'a),所以我们说 other 也应该在相同的生命周期内有效作为&amp;self参数,即'a的生命周期?

    这有点不准确,第二个示例中&amp;self 的生命周期不是 'a,而是 'a 为界。如果我们通过反转 Rust 的生命周期省略规则来扩展它,第二个示例将不再适用:

    struct Important<'a> {
        part: &'a str,
    }
    
    impl<'a> Important<'a> {
        fn larger<'b>(self: &'b Important<'a>, other: &'a str) -> &'b str {
            if self.part.len() > other.len() {
                self.part
            } else {
                other
            }
        }
    }
    

    self 受'a 限制的原因是因为&amp;'b Important&lt;'a&gt; 暗示'b: 'a 或者简单地说'a'b 更长寿” 必须为真否则引用可能失效。如果我们扩展第一个示例,self 的类型再次变为&amp;'b Important&lt;'a&gt;。第一个和第二个示例之间的唯一区别是other 的类型,第一个是&amp;'b str,第二个是&amp;'a str,但这是一个无关紧要的细节,因为返回值的类型是&amp;'b str,它是受约束的在'b 的生命周期内,我们知道'b: 'a 所以在功能上这两个例子是相同的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      • 2018-08-12
      • 1970-01-01
      • 2021-08-02
      • 2015-02-19
      相关资源
      最近更新 更多