简体   繁体   English

为什么要求AddAssign作为超级特征的特征也要求它是大小的?

[英]Why does a trait requiring AddAssign as a supertrait also require it to be Sized?

I have a trait, and to implement that trait, I would like to require the implementor to implement AddAssign ; 我有一个特点,为了实现这个特性,我想要求实现者实现AddAssign ; however, doing that results in my trait seemingly needing to require Sized : 然而,这样做会导致我的特质似乎需要Sized

trait Foo: ::std::ops::AddAssign {}

trait Bar: Iterator {}

(playground) (操场)

Bar compiles fine; Bar汇编很好; Foo , however: 然而, Foo

error[E0277]: the trait bound `Self: std::marker::Sized` is not satisfied
 --> src/main.rs:1:1
  |
1 | trait Foo: ::std::ops::AddAssign {}
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `Self` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `Self`
  = help: consider adding a `where Self: std::marker::Sized` bound
  = note: required by `std::ops::AddAssign`

If I add + Sized to the trait bounds, all is fine, but… why do I need to do this? 如果我将+ Sized添加到特征边界,一切都很好,但是......为什么需要这样做? Why doesn't AddAssign need this? 为什么AddAssign不需要这个?

Let's look at the definition of the trait: 让我们看一下特质的定义:

pub trait AddAssign<Rhs = Self> {
    fn add_assign(&mut self, rhs: Rhs);
}

That is, trait Foo: ::std::ops::AddAssign is equivalent to trait Foo: ::std::ops::AddAssign<Foo> and add_assign takes a Rhs as its second parameter, hence Rhs needs to be sized. 也就是说, trait Foo: ::std::ops::AddAssign相当于trait Foo: ::std::ops::AddAssign<Foo>add_assignRhs作为其第二个参数,因此需要调整Rhs大小。

Note that trait Foo: ::std::ops::AddAssign<u32> does not require Foo to be sized. 请注意, trait Foo: ::std::ops::AddAssign<u32>不需要调整Foo大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM