简体   繁体   English

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

[英]How to set generic trait as type of function argument?

There is generic trait Graph 有通用特征Graph

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;
}

and its implementation AdjacencyList struct 及其实现AdjacencyList结构

struct AdjacencyList<T> {
    // ...
}
impl<T> Graph<T> for AdjacencyList<T> {
    // ...
}

I need a function that takes an empty graph and does something with it. 我需要一个带有空图并对其执行某些操作的函数。

fn create_sample_graph<T: Graph<&'static str>>(graph: &mut T) {
    let key1 = graph.add_node("node1");
    // ...
}

I create an instance of AdjacencyList with the &str type and send it to the function. 我用&str类型创建一个AdjacencyList实例,并将其发送给函数。

fn main() {
    let mut adjacency_list = AdjacencyList::<&str>::new();
    create_sample_graph(adjacency_list);
}

But the compiler fails with the following error: 但是编译器失败并显示以下错误:

error: mismatched types:
 expected `&mut _`,
    found `AdjacencyList<&str>`
(expected &-ptr,
    found struct `AdjacencyList`) [E0308]
create_sample_graph(adjacency_list);
                    ~~~~~~~~~~~~~~

How can I set the trait as a type of the function's argument and pass there a struct that implements this trait? 如何将特征设置为函数参数的类型,并在其中传递实现该特征的结构?

You need to pass &mut adjacency_list . 您需要传递&mut adjacency_list That's what the error is saying, and it's correct: you've defined the function as taking a &mut pointer, but you're passing the value directly. 这就是错误的意思,这是正确的:您已将函数定义为采用&mut指针,但直接传递了值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM