Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to get associated type from struct?

Tags:

rust

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.

like image 711
user1244932 Avatar asked Jan 03 '23 16:01

user1244932


1 Answers

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

like image 72
E_net4 stands with Ukraine Avatar answered Jan 13 '23 04:01

E_net4 stands with Ukraine