在Rust中,当我们想要一个包含引用的结构时,我们通常会定义它们的生命周期:
struct Foo<'a> {
x: &'a i32,
y: &'a i32,
}
Run Code Online (Sandbox Code Playgroud)
但是也可以为同一结构中的不同引用定义多个生命周期:
struct Foo<'a, 'b> {
x: &'a i32,
y: &'b i32,
}
Run Code Online (Sandbox Code Playgroud)
什么时候这样做有用?有人可以提供一些示例代码,这些代码在两个生命周期都'a没有编译但是在生命周期时编译'a并且'b(反之亦然)?
我的意思是:
fn minimum<'a, 'b>(x: &'a mut i32, y: &'b mut i32) -> &'min(a, b) mut i32 {
(x < y) ? x : y
}
Run Code Online (Sandbox Code Playgroud)
我们不知道在生命周期中将选择哪个引用,但编译器知道两个引用在哪个范围内仍然有效,并且可以安全地使用返回的引用.
可以提及的解决方法:
fn minimum<'a, 'b> where 'b: 'a (x: &'a i32, y: 'b i32) -> &'a i32 {
(x < y) ? x : y
}
Run Code Online (Sandbox Code Playgroud)
实际上并不是解决方案,因为在调用函数时我们必须处理两种情况:when 'a: 'b和'b: 'a
struct Point {
x: u32,
y: u32,
}
struct Line<'a> {
start: &'a Point,
end: &'a Point,
}
Run Code Online (Sandbox Code Playgroud)
Here, the only possible option for the start and end fields is to have a lifetime the same or longer than the Line variable that contains them. I can't even imagine how one will go about using a lifetime specifier to say that the fields have a shorter lifespan.
Why do I have to explicitly specify a lifetime here? Is elision not …
终身省略的第三条规则说
如果有多个输入生命周期参数,但其中之一是
&self或&mut self因为这是一种方法,则生命周期self被分配给所有输出生命周期参数。这使得编写方法更好。
这是描述此功能发生了什么的教程
fn announce_and_return_part(&self, announcement: &str) -> &str
Run Code Online (Sandbox Code Playgroud)
有两个输入生命周期,所以 Rust 应用第一个生命周期省略规则并给出它们
&self和announcement它们自己的生命周期。然后,因为其中一个参数是&self,返回类型获得 的生命周期&self,并且所有生命周期都已被考虑在内。
我们可以证明所有生命周期都没有考虑在内,因为它的生命周期可能与announcement不同&self:
struct ImportantExcerpt<'a> {
part: &'a str,
}
impl<'a> ImportantExcerpt<'a> {
fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("Attention please: {}", announcement);
announcement
}
}
fn main() {
let i = ImportantExcerpt { part: "IAOJSDI" };
let test_string_lifetime;
{
let a = String::from("xyz");
test_string_lifetime = i.announce_and_return_part(a.as_str());
} …Run Code Online (Sandbox Code Playgroud)