什么时候在一个结构中定义多个生存期有用? [英] When is it useful to define multiple lifetimes in a struct?

查看:66
本文介绍了什么时候在一个结构中定义多个生存期有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rust中,当我们希望一个结构包含引用时,通常会这样定义它们的生存期:

In Rust, when we want a struct to contain references, we typically define their lifetimes as such:

struct Foo<'a> {
    x: &'a i32,
    y: &'a i32,
}

但是也可以在同一结构中为不同的引用定义多个生存期:

But it's also possible to define multiple lifetimes for different references in the same struct:

struct Foo<'a, 'b> {
    x: &'a i32,
    y: &'b i32,
}

何时才有用?有人可以提供一些示例代码,当两个生存期都为'a时不编译,但是当生存期分别为'a'b时才编译(反之亦然)吗?

When is it ever useful to do this? Can someone provide some example code that doesn't compile when both lifetimes are 'a but does compile when the lifetimes are 'a and 'b (or vice versa)?

推荐答案

熬夜太晚之后,我提出了一个影响生命周期的示例案例.这是代码:

After staying up way too late, I was able to come up with an example case where the lifetimes matter. Here is the code:

static ZERO: i32 = 0;

struct Foo<'a, 'b> {
    x: &'a i32,
    y: &'b i32,
}

fn get_x_or_zero_ref<'a, 'b>(x: &'a i32, y: &'b i32) -> &'a i32 {
    if *x > *y {
        return x
    } else {
        return &ZERO
    }
}

fn main() {
    let x = 1;
    let v;
    {
        let y = 2;
        let f = Foo { x: &x, y: &y };
        v = get_x_or_zero_ref(&f.x, &f.y);
    }
    println!("{}", *v);
}

如果要将Foo的定义更改为此:

If you were to change the definition of Foo to this:

struct Foo<'a> {
    x: &'a i32,
    y: &'a i32,
}

然后代码将无法编译.

基本上,如果要在要求其参数具有不同生存期的任何函数上使用该结构的字段,则该结构的字段也必须具有不同的生存期.

Basically, if you want to use the fields of the struct on any function that requires it's parameters to have different lifetimes, then the fields of the struct must have different lifetimes as well.

这篇关于什么时候在一个结构中定义多个生存期有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆