简体   繁体   中英

How to set generic trait as type of function argument?

There is generic trait 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

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.

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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