这段代码:
use std::collections::HashMap;
struct MyNode;
struct MyEdge;
struct Graph<N, E> {
h: HashMap<N, Vec<E>>,
}
type MyGraph = Graph<MyNode, MyEdge>;
fn main() {
let x: MyGraph::N;//XXX
println!("Results:")
}
Run Code Online (Sandbox Code Playgroud)
无法编译错误:
error[E0223]: ambiguous associated type
--> /home/xxx/.emacs.d/rust-playground/at-2017-07-26-164119/snippet.rs:21:12
|
21 | let x: MyGraph::N;
| ^^^^^^^^^^ ambiguous associated type
|
= note: specify the type using the syntax `<Graph<MyNode, MyEdge> as Trait>::N`
Run Code Online (Sandbox Code Playgroud)
有没有办法从中获取N类型Graph<MyNode, MyEdge>?
我创建了一个type =不复制节点类型定义的别名(),所以在XXX我可以写的标记点上它会很棒let x: MyNode但是let x: expression with MyGraph as argument.
代码中没有关联的类型参数.关联类型仅适用于特征,允许您编写以下内容:
trait Graph {
type Node;
type Edge;
}
Run Code Online (Sandbox Code Playgroud)
特别是,你在struct(N和E)中有普通的类型参数.如果没有共同特征,则必须手动解析类型.无论如何,这里做起来并不复杂.
struct GraphImpl<N, E> {
h: HashMap<N, Vec<E>>,
}
type MyGraph = GraphImpl<MyNode, MyEdge>;
let x: MyNode;
Run Code Online (Sandbox Code Playgroud)
但是,如果你这样做实现这一Graph特质对你的结构:
impl<N, E> Graph for GraphImpl<N, E> {
type Node = N;
type Edge = E;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以检索此问题中显示的关联类型:
let x: <MyGraph as Graph>::Node;
Run Code Online (Sandbox Code Playgroud)