我想不出一种方法来编译这段代码--cfg on_trait
:
trait DigitCollection: Sized {
type Iter: Iterator<Item = u8>;
fn digit_iter(self) -> Self::Iter;
#[cfg(on_trait)]
fn digit_sum(self) -> u32 {
self.digit_iter()
.map(|digit: u8| digit as u32)
.fold(0, |sum, digit| sum + digit)
}
}
#[cfg(not(on_trait))]
fn digit_sum<T: DigitCollection>(collection: T) -> u32 {
collection.digit_iter()
.map(|digit: u8| digit as u32)
.fold(0, |sum, digit| sum + digit)
}
fn main() {
}
这on_trait
失败了:
trait.rs:7:14: 7:26 error: type annotations required: cannot resolve `<<Self as DigitCollection>::Iter as core::iter::Iterator>::Item == u8` [E0284]
trait.rs:7 self.digit_iter()
^~~~~~~~~~~~
error: aborting due to previous error
没有on_trait
,它编译得很好。请注意,该not(on_trait)
变体的不同之处仅在于它是一个自由函数而不是默认方法。
编辑:我打开了一个问题:rust-lang/rust#22036