[英]Why does the compiler infer different lifetimes for a trait and its implementation?
I'm currently using rustlearn to evaluate different classification models. 我目前正在使用rustlearn来评估不同的分类模型。 The problem I ran into basically boils down to this:
我遇到的问题基本归结为:
trait Foo<T> {
fn bar(&self, x: T);
}
struct Baz;
struct Smth;
impl<'a> Foo<&'a Smth> for Baz {
fn bar(&self, x: &Smth) {}
}
fn main() {
let some_foo: Box<Baz> = Box::new(Baz {}); // ok
// let some_foo: Box<Foo<&Smth>> = Box::new(Baz {}); // not ok
let x = Smth {};
some_foo.bar(&x);
}
While it is possible to type some_foo
as Box<Baz>
, it is not possible to use Box<Foo<&Smth>>
instead, since it will cause the compiler to complain about &x
being dropped (at the end of main
) while still borrowed (in bar
). 虽然可以输入
some_foo
作为Box<Baz>
,但是不可能使用Box<Foo<&Smth>>
,因为它会导致编译器抱怨&x
被丢弃(在main
的末尾),同时仍然借用(在bar
)。 This is (I think) due to the fact that x
is created after some_foo
, hence x
gets dropped before some_foo
. 这是(我认为),因为
x
是在 some_foo
之后 some_foo
,因此x
在 some_foo
之前被删除。 Moving the creation of x
such that it occurs before the creation of some_foo
would be a solution; 移动
x
的创建使其在创建some_foo
之前发生将是一个解决方案; but let's assume that's not possible¹. 但我们假设不可能¹。
I still don't quite get why the code is valid for some_foo: Box<Baz>
but not for some_foo: Box<Foo<&Smth>>
. 我仍然不明白为什么代码对
some_foo: Box<Baz>
有效some_foo: Box<Baz>
但不是some_foo: Box<Foo<&Smth>>
。 What is it that the compiler cannot know (otherwise it wouldn't need to complain)? 什么是编译器无法知道(否则它不需要抱怨)?
¹ because you have a collection of models which you wish to crossvalidate , ie model.fit(x, y)
where x, y
are subsets of larger (X, Y)
. ¹因为您有一组希望交叉验证的模型,即
model.fit(x, y)
,其中x, y
是较大(X, Y)
子集。
The boxed trait object needs to work with all lifetimes for the reference to Smth
: 盒装特征对象需要使用所有生命周期来引用
Smth
:
let some_foo: Box<for<'a> Foo<&'a Smth>> = Box::new(Baz {});
Maybe someone else can explain why the compiler couldn't derive a working lifetime :) 也许其他人可以解释为什么编译器无法导出工作生命周期:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.