2017-07-26 48 views
1

此代碼:任何方式從結構中獲取關聯的類型?

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:") 

} 

失敗,錯誤編譯:

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` 

有沒有辦法從Graph<MyNode, MyEdge>得到N類型?

我創建了一個別名(type =)不重複的節點類型定義, 所以它會在標記XXX點是巨大的,我可以不寫,但let x: MyNodelet x: expression with MyGraph as argument

+1

Th似乎不必要的複雜;爲什麼不只是'讓x:MyNode;'?有多種節點類型? – ljedrz

+0

@ljedrz嗯,爲了防止代碼重複,在我的程序中有'let x:MyNode'這樣的地方,當我更改此圖的Node類型時,我必須修復所有這些地方。 – user1244932

回答

7

代碼中沒有關聯的類型參數。 Associated types只適用於特性,它允許你這樣寫:

trait Graph { 
    type Node; 
    type Edge; 
} 

特別是,你必須在結構(NE)普通型參數。沒有共同的特徵,你必須手動解決這個類型。無論如何,這並不複雜。

struct GraphImpl<N, E> { 
    h: HashMap<N, Vec<E>>, 
} 

type MyGraph = GraphImpl<MyNode, MyEdge>; 

let x: MyNode; 

不過,如果你實現這個Graph特質對你的結構:

impl<N, E> Graph for GraphImpl<N, E> { 
    type Node = N; 
    type Edge = E; 
} 

然後你可以檢索關聯的類型,如圖this question

let x: <MyGraph as Graph>::Node; 

Playground