具有依赖于关联类型边界的默认方法的特征

Traits with default methods that depend on a bound of an associated type

我想不出让这段代码用 --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

此代码现在可以按需要编译:

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() {}