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

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

问题描述

在 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天全站免登陆