Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disambiguate associated type in struct

Tags:

rust

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?

like image 966
Abhishek Chanda Avatar asked Mar 13 '23 08:03

Abhishek Chanda


2 Answers

"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() {}
like image 75
Shepmaster Avatar answered Mar 16 '23 00:03

Shepmaster


it's ambiguous because it could be associated constants. You need to tell the compiler you are referring to an associated type through ::, not a constant.

This is the same as the C++ typename, which is used to disambiguate type and constant of generic parameters.

like image 34
Izana Avatar answered Mar 16 '23 00:03

Izana