This code:
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:")
}
Fails to compile with the error:
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`
Is there any way to get N
type from Graph<MyNode, MyEdge>
?
I created an alias (type =
) to not duplicate node type definitions,
so it would be great at the point marked XXX
I could write not let x: MyNode
but let x: expression with MyGraph as argument
.
There are no associated type parameters in your code. Associated types are applicable to traits only, which allow you to write this:
trait Graph {
type Node;
type Edge;
}
In particular, you have ordinary type parameters in the struct (N
and E
). Without a common trait, you have to resolve the type manually. It's not something complicated to do here anyway.
struct GraphImpl<N, E> {
h: HashMap<N, Vec<E>>,
}
type MyGraph = GraphImpl<MyNode, MyEdge>;
let x: MyNode;
However, if you do implement this Graph
trait for your struct:
impl<N, E> Graph for GraphImpl<N, E> {
type Node = N;
type Edge = E;
}
Then you can retrieve the associated type as shown in this question:
let x: <MyGraph as Graph>::Node;
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With