簡體   English   中英

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

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

我有一個特點,為了實現這個特性,我想要求實現者實現AddAssign ; 然而,這樣做會導致我的特質似乎需要Sized

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

trait Bar: Iterator {}

(操場)

Bar匯編很好; 然而, 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`

如果我將+ Sized添加到特征邊界,一切都很好,但是......為什么需要這樣做? 為什么AddAssign不需要這個?

讓我們看一下特質的定義:

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

也就是說, trait Foo: ::std::ops::AddAssign相當於trait Foo: ::std::ops::AddAssign<Foo>add_assignRhs作為其第二個參數,因此需要調整Rhs大小。

請注意, trait Foo: ::std::ops::AddAssign<u32>不需要調整Foo大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM