相关疑难解决方法(0)

何时在结构中定义多个生命周期是有用的?

在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(反之亦然)?

lifetime rust

30
推荐指数
3
解决办法
1759
查看次数

有没有办法选择两个生命周期中较小的一个?

我的意思是:

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

lifetime rust

12
推荐指数
1
解决办法
93
查看次数

Why can the lifetimes not be elided in a struct definition?

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 …

lifetime rust

11
推荐指数
1
解决办法
1600
查看次数

生命周期省略的第三条规则是否涵盖了结构实现的所有情况?

终身省略的第三条规则说

如果有多个输入生命周期参数,但其中之一是&self&mut self因为这是一种方法,则生命周期self被分配给所有输出生命周期参数。这使得编写方法更好。

这是描述此功能发生了什么的教程

fn announce_and_return_part(&self, announcement: &str) -> &str
Run Code Online (Sandbox Code Playgroud)

有两个输入生命周期,所以 Rust 应用第一个生命周期省略规则并给出它们&selfannouncement它们自己的生命周期。然后,因为其中一个参数是&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)

lifetime rust

6
推荐指数
1
解决办法
202
查看次数

标签 统计

lifetime ×4

rust ×4