为什么对泛型函数中特征的引用必须实现“Sized”?
Why does a reference to a trait in a generic function have to implement `Sized`?
我有一个函数 returns 对特征的引用 (trait_ref()
) 和另一个函数引用通用特征实现 (take_trait_ref_generic
)。
但是,无法将从第一个函数获得的引用传递给第二个函数。 Rustc 抱怨 "the trait std::marker::Sized
is not implemented for SomeTrait
".
虽然是这样,但为什么一定要执行Sized
?反正是个参考。
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
:
明确选择退出该要求
fn take_trait_ref_generic<T>(generic_trait_ref: &T)
where
T: ?Sized + SomeTrait
{}
我有一个函数 returns 对特征的引用 (trait_ref()
) 和另一个函数引用通用特征实现 (take_trait_ref_generic
)。
但是,无法将从第一个函数获得的引用传递给第二个函数。 Rustc 抱怨 "the trait std::marker::Sized
is not implemented for SomeTrait
".
虽然是这样,但为什么一定要执行Sized
?反正是个参考。
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
:
fn take_trait_ref_generic<T>(generic_trait_ref: &T)
where
T: ?Sized + SomeTrait
{}