Skip to content

Can't write default methods that depend on a bound of an associated type of their traits #22036

Closed
@renato-zannon

Description

@renato-zannon

That's a mouthful! To exemplify:

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

This doesn't compile with --cfg on_trait, even though it does without it. Note that the only difference between the two configurations is that the function on not(on_trait) is a free function instead of a default method.

With on_trait, this fails with:

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

Tested on rustc 1.0.0-dev (f3573aa83 2015-02-06 05:52:20 +0000)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-trait-systemArea: Trait system

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions