【发布时间】: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
}
}
}
我猜在第一个版本中我们会指示编译器
-
找到一个生命周期
'b使得&self和引用other在此期间都有效(如果它们重叠,可能是两个生命周期中较短的那个) -
确保返回的引用仅在该生命周期内使用
'b,因为在外部它可能成为悬空引用。
第二版代码的作用是什么? Rust 书中的生命周期省略规则之一说,在结构方法中,返回的引用被分配了 &self 参数的生命周期(这里是 'a),所以我们说 other 也应该是有效的与&self 参数的生命周期相同,即'a 的生命周期?
从语义上讲,这是相同的代码还是这些版本的行为是否会因other 和结构的生命周期而有所不同?
【问题讨论】:
标签: methods struct rust reference lifetime