消除结构中的关联类型的歧义

时间:2016-02-08 03:23:09

标签: rust

我正在尝试运行此

use std::collections::BTreeSet;

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

fn main() {}

Playground

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

为什么关联类型不明确?

2 个答案:

答案 0 :(得分:4)

&#34;不明确&#34;这里似乎有点误导性的措辞。此示例生成相同的错误消息:

struct Foo;

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

fn main() {}

我不确定,但我发现标准库中不太可能存在名为Baz的关联类型,更不可能有两种类型使其模糊不清!< / p>

更有可能的是,这种语法不够具体。 可以多个可能具有Baz关联类型的特征是完全合理的。因此,您必须指定要使用相关类型的特征:

struct Foo;

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

fn main() {}

答案 1 :(得分:2)

它不明确,因为它可能是 associated constants。您需要告诉编译器您指的是 associated type::,而不是常量。

这与 C++ typename 相同,用于消除泛型参数的类型和常量的歧义。

相关问题