Generics 如何将泛型特征设置为函数参数的类型?

Generics 如何将泛型特征设置为函数参数的类型?,generics,struct,rust,traits,Generics,Struct,Rust,Traits,有通用特征图 type NodeKey = usize; type EdgeWeight = usize; trait Graph<T> { fn add_node(&mut self, node: T) -> NodeKey; fn add_edge(&mut self, begin: NodeKey, end: NodeKey, weight: EdgeWeight); fn new() -> Self; } 我需要一个函数

有通用特征

type NodeKey = usize;
type EdgeWeight = usize;

trait Graph<T> {
    fn add_node(&mut self, node: T) -> NodeKey;
    fn add_edge(&mut self, begin: NodeKey, end: NodeKey, weight: EdgeWeight);
    fn new() -> Self;
}
我需要一个函数,它接受一个空的图形并用它做一些事情

fn create_sample_graph<T: Graph<&'static str>>(graph: &mut T) {
    let key1 = graph.add_node("node1");
    // ...
}
但编译器失败,出现以下错误:

error: mismatched types:
 expected `&mut _`,
    found `AdjacencyList<&str>`
(expected &-ptr,
    found struct `AdjacencyList`) [E0308]
create_sample_graph(adjacency_list);
                    ~~~~~~~~~~~~~~
错误:不匹配的类型:
应为“&mut”,
找到`邻接列表`
(预期和-ptr,
已找到结构“邻接列表”)[E0308]
创建样本图(邻接列表);
~~~~~~~~~~~~~~

如何将trait设置为函数参数的一种类型,并向其传递实现此trait的结构?

您需要传递
&mut adjacence\u list
。这就是错误所说的,它是正确的:您已将函数定义为使用
&mut
指针,但您直接传递值。

您需要传递
&mut adjacence\u list
。这就是错误所说的,它是正确的:您已将函数定义为使用
&mut
指针,但您直接传递值。

是。你是对的!我是铁锈的初学者,他的所有权规则对我来说并不明显。正因为如此,我经常寻找错误问题的答案。非常感谢。是的。你是对的!我是铁锈的初学者,他的所有权规则对我来说并不明显。正因为如此,我经常寻找错误问题的答案。非常感谢你。
fn main() {
    let mut adjacency_list = AdjacencyList::<&str>::new();
    create_sample_graph(adjacency_list);
}
error: mismatched types:
 expected `&mut _`,
    found `AdjacencyList<&str>`
(expected &-ptr,
    found struct `AdjacencyList`) [E0308]
create_sample_graph(adjacency_list);
                    ~~~~~~~~~~~~~~