我无法找到一种方法来使用--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
答案 0 :(得分:1)
此代码现在可以根据需要编译:
trait DigitCollection: Sized {
type Iter: Iterator<Item = u8>;
fn digit_iter(self) -> Self::Iter;
fn digit_sum(self) -> u32 {
self.digit_iter()
.map(|digit: u8| digit as u32)
.fold(0, |sum, digit| sum + digit)
}
}
fn main() {}