为什么我需要为不是该结构成员的结构的通用参数提供生命周期? [英] Why do I need to provide lifetimes for a struct's generic parameters which are not members of the struct?

查看:46
本文介绍了为什么我需要为不是该结构成员的结构的通用参数提供生命周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力弄清泛型和生命周期相互作用的方式.考虑:

I'm trying to get my head around the way that generics and lifetimes interact. Consider:

use std::ops::Add;

struct Gloop<'a, T: Add> {
    wumpus: &'a Wumpus<T>,
}

trait Wumpus<T: Add> {
    fn fleeb(&self, x: &T) -> bool;
}

struct Mimsy {
    jubjub: f64,
}

impl<T: Add> Wumpus<T> for Mimsy {
    fn fleeb(&self, x: &T) -> bool {
        return (x + x) > 0;
    }
}

fn main() {
    let a = Mimsy { jubjub: 1. };
    let b = Gloop::<i32> { wumpus: &a };
    println!("{}", b.fleeb(1));
}

哪个产量:

error[E0309]: the parameter type `T` may not live long enough
 --> src/main.rs:4:5
  |
3 | struct Gloop<'a, T: Add> {
  |                  -- help: consider adding an explicit lifetime bound `T: 'a`...
4 |     wumpus: &'a Wumpus<T>,
  |     ^^^^^^^^^^^^^^^^^^^^^
  |
note: ...so that the reference type `&'a Wumpus<T> + 'a` does not outlive the data it points at
 --> src/main.rs:4:5
  |
4 |     wumpus: &'a Wumpus<T>,
  |     ^^^^^^^^^^^^^^^^^^^^^

程序中的哪个对象可能寿命不长? GloopMimsy(或任何Wumpus<T>)中都没有存储过T.

Which object in my program is the one which may not live long enough? Nowhere in either Gloop or Mimsy (or any Wumpus<T>) is a T ever stored.

推荐答案

注意:我回答了这个问题,但认为问题实际上是

Note: I answered this, but think the question is actually a duplicate of

参数类型'C'可能寿命不足"

如果其他人同意,可以删除此答案.

This answer can be deleted if others agree.

GloopMimsy(或任何Wumpus<T>)中都没有存储过T.

Nowhere in either Gloop or Mimsy (or any Wumpus<T>) is a T ever stored.

Rust不在乎您做什么,但在乎您可以做什么.这两种结构之间没有签名差异:

Rust doesn't care about what you do, but what you could do. There are no signature differences between these two structs:

struct Alpha<T> {
    a: T,
}

struct Beta<T> {
    b: fn(&T),
}

即,您不能说出两者之间的区别,而Beta可能会变成Alpha,而无需对消费者进行明显的外部更改.一旦有了通用类型,就需要处理所有可能.

Namely, you can't tell the difference between the two and Beta could become Alpha without noticeable external changes to a consumer. Once you have a generic type, you need to handle any possibility.

您可以添加T: 'static或添加生存期并添加T: 'a.

You can either add T: 'static or add a lifetime and add T: 'a.

另请参阅:

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