【发布时间】:2021-04-13 17:48:33
【问题描述】:
作为 Rust 编程的初学者,我对 Size trait 与通用 trait 的结合感到有些困惑。 我的自定义特征定义了一个方法,它接受两个对象并将它们组合成一个新对象。因为原始对象在组合后过期,方法应该取得参数的所有权。 我还返回了一个自定义错误类型的结果,因为组合可能会失败,我想给调用者一个失败的原因。
有问题的特征是:
pub trait Combinable<T> {
fn combine(self, other: T) -> CombinationResult<T>;
}
struct CombinationError;
type CombinationResult<T> = std::result::Result<dyn Combinable<T>, CombinationError>
编译这段代码时出现以下错误:
error[E0277]: the size for values of type `(dyn Combinable<T> + 'static)` cannot be known at compilation time
|
7 | fn combine(self, other: T) -> CombinationResult<T>;
| ^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
241 | pub enum Result<T, E> {
| - required by this bound in `std::result::Result`
|
= help: the trait `Sized` is not implemented for `(dyn Combinable<T> + 'static)`
我尝试将泛型类型参数 T 限制为 Sized(即 pub trait Combinable<T: Sized>),但没有奏效。我也在类型别名声明中尝试了同样的方法,也无济于事。
我是否遗漏/忽略了什么?
【问题讨论】: