Disambiguate associated type in struct

2019-07-03 17:16发布

问题:

I am trying to run this

use std::collections::BTreeSet;

pub struct IntoIter<T> {
    iter: BTreeSet<T>::IntoIter,
}

fn main() {}

Playground

This fails with

error[E0223]: ambiguous associated type
 --> src/main.rs:4:11
  |
4 |     iter: BTreeSet<T>::IntoIter,
  |           ^^^^^^^^^^^^^^^^^^^^^ ambiguous associated type
  |

Why is the associated type ambiguous?

回答1:

"Ambiguous" seems like a bit of misleading wording here. This example produces the same error message:

struct Foo;

pub struct Bar {
    iter: Foo::Baz,
}

fn main() {}

I'm not certain, but I'd find it unlikely that there is an associated type named Baz in the standard library, much less likely that there are two to make it ambiguous!

What's more likely is that this syntax is simply not specific enough. It's completely plausible that there could be multiple traits that could have a Baz associated type. Because of that, you have to specify which trait you want to use the associated type from:

struct Foo;

pub struct Bar {
    iter: <Vec<u8> as IntoIterator>::IntoIter,
}

fn main() {}


标签: rust