fn foo<'a, T>()
where T : 'a
{
//code a
}
fn foo()
{
//code b
}
其中,类型T是具有生存期参数的任何类型. 在代码a中可以做什么,而在代码b中不能做什么?
我希望它们是完全相同的,因为我不明白其中的区别和生命周期界限的具体含义.如果第一个函数可以更容易地解释用例(如参数),则可以建议对其进行添加.
fn foo<'a, T>()
where T : 'a
{
//code a
}
fn foo()
{
//code b
}
其中,类型T是具有生存期参数的任何类型. 在代码a中可以做什么,而在代码b中不能做什么?
我希望它们是完全相同的,因为我不明白其中的区别和生命周期界限的具体含义.如果第一个函数可以更容易地解释用例(如参数),则可以建议对其进行添加.
您可以在下面的代码中看到BIND是必需的:
trait Elem {}
struct List<'a> {
v: Vec<Box<dyn Elem + 'a>>,
}
impl<'a> List<'a> {
fn push<T: Elem>(&mut self, t: T) {
self.v.push(Box::new(t));
}
}
error[E0309]: the parameter type `T` may not live long enough
--> src/lib.rs:9:21
|
9 | self.v.push(Box::new(t));
| ^^^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds
|
help: consider adding an explicit lifetime bound...
|
8 | fn push<T: Elem + 'a>(&mut self, t: T) {
| ++++
从本质上讲,泛型类型可以有任意生存期,但有时需要在只允许特定生存期的上下文中使用泛型类型.在这种情况下,List<'a>
只能保存生命周期 至少为'a
的元素.因此,对于这些情况,存在T: 'a
的约束.T: 'static
是这种语法最常见的情况,它表示该类型可能根本不包含任何本地引用.