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?