5

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: MyNodebut let x: expression with MyGraph as argument.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user1244932
  • 7,352
  • 5
  • 46
  • 103
  • 1
    This seems unnecessarily complicated; why not just `let x: MyNode;`? Are there multiple node types? – ljedrz Jul 26 '17 at 14:01
  • 1
    @ljedrz Hmm, to prevent code duplication, such places with `let x: MyNode` a lot in my program, when I change `Node` type of this graph I have to fix all those places. – user1244932 Jul 26 '17 at 15:56

1 Answers1

9

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

E_net4
  • 27,810
  • 13
  • 101
  • 139