# 关联类型

2018-08-12 22:03 更新

## 关联类型

``````trait Graph<N, E> {
fn has_edge(&self, &N, &N) -> bool;
fn edges(&self, &N) -> Vec<E>;
// etc
}``````

``fn distance<N, E, G: Graph<N, E>>(graph: &G, start: &N, end: &N) -> u32 { ... }``

``````trait Graph {
type N;
type E;

fn has_edge(&self, &Self::N, &Self::N) -> bool;
fn edges(&self, &Self::N) -> Vec<Self::E>;
// etc
}``````

``fn distance<G: Graph>(graph: &G, start: &G::N, end: &G::N) -> uint { ... }``

## 定义关联类型

``````trait Graph {
type N;
type E;

fn has_edge(&self, &Self::N, &Self::N) -> bool;
fn edges(&self, &Self::N) -> Vec<Self::E>;
}``````

``````use std::fmt;

trait Graph {
type N: fmt::Display;
type E;

fn has_edge(&self, &Self::N, &Self::N) -> bool;
fn edges(&self, &Self::N) -> Vec<Self::E>;
}``````

## 关联类型的实现

``````struct Node;

struct Edge;

struct MyGraph;

impl Graph for MyGraph {
type N = Node;
type E = Edge;

fn has_edge(&self, n1: &Node, n2: &Node) -> bool {
true
}

fn edges(&self, n: &Node) -> Vec<Edge> {
Vec::new()
}
}``````

## 关联类型的特征对象

``````let graph = MyGraph;
let obj = Box::new(graph) as Box<Graph>;``````

``````error: the value of the associated type `E` (from the trait `main::Graph`) must
be specified [E0191]
let obj = Box::new(graph) as Box<Graph>;

24:44 error: the value of the associated type `N` (from the trait
`main::Graph`) must be specified [E0191]
let obj = Box::new(graph) as Box<Graph>;``````

``````let graph = MyGraph;
let obj = Box::new(graph) as Box<Graph<N=Node, E=Edge>>;``````

N=Node 语法允许我们为 N 类型参数提供一个具体的类型，Node。E=Edge 也一样。如果我们没有提供这个约束，我们无法确定哪一个 impl 与这个特征对象相匹配。

App下载