为什么在泛型函数中对特征的引用必须实现“Sized"? [英] Why does a reference to a trait in a generic function have to implement `Sized`?
问题描述
我有一个函数返回对 trait 的引用(trait_ref()
)和另一个函数,它接受对通用 trait 实现的引用(take_trait_ref_generic
).
I have a function that returns a reference to a trait (trait_ref()
) and another function that takes a reference to a generic trait implementation (take_trait_ref_generic
).
但是,无法将我从第一个函数获得的引用传递给第二个函数.Rustc 抱怨特征 std::marker::Sized
没有为 SomeTrait
实现".
However, it's not possible to pass the reference I get from the first function to the second one. Rustc complains that "the trait std::marker::Sized
is not implemented for SomeTrait
".
即使是这样,为什么它必须实现Sized
?反正都是参考.
Even though that's true, why does it have to implement Sized
? It's a reference anyway.
trait SomeTrait {}
struct TraitImpl;
impl SomeTrait for TraitImpl {}
struct Container {
trait_impl: TraitImpl,
}
impl Container {
fn trait_ref(&self) -> &SomeTrait {
&self.trait_impl
}
}
fn take_trait_ref_generic<T: SomeTrait>(generic_trait_ref: &T) {}
fn main() {
let container = Container { trait_impl: TraitImpl };
/*Not possible*/
take_trait_ref_generic(container.trait_ref());
}
推荐答案
默认情况下,所有 函数的泛型类型都隐式地具有 Sized
绑定,无论它们如何用过的.您需要使用 ?Sized
明确选择退出该要求:
By default, all generic types on functions implicitly have the Sized
bound, regardless of how they are used. You need to explicitly opt-out of that requirement using ?Sized
:
fn take_trait_ref_generic<T>(generic_trait_ref: &T)
where
T: ?Sized + SomeTrait
{}
这篇关于为什么在泛型函数中对特征的引用必须实现“Sized"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!