Newbie question: I want to use the petgraph rust crate. The graph should be a part of the struct MyGraph
. For this, I need to wrap some functions to make them acessible from outside:
use petgraph::graph::DiGraph;
use petgraph::adj::NodeIndex;
#[derive(Default)]
struct MyNode {}
#[derive(Default)]
struct MyGraph {
g: DiGraph<MyNode,()>
}
impl MyGraph {
pub fn add_node(&mut self, node: MyNode) -> NodeIndex {
self.g.add_node(node) // does not compile: return value is u32 != NodeIndex
}
pub fn update_edge(&mut self, a: NodeIndex, b: NodeIndex) {
self.g.update_edge(a, b, ()); // does not compile: a: NodeIndex expected, got u32
}
}
fn main() {
let mut my_graph=MyGraph::default();
let node1=my_graph.add_node(MyNode::default());
let node2=my_graph.add_node(MyNode::default());
my_graph.update_edge(node1,node2);
}
The rust compiler however complains the an u32 is returned by the self.g.add_node()
function, which is not the case if you call the function directly (and it's documented to return a NodeIndex). The smae problem applies to the self.g.update_edge()
function. What would be the correct parameter type to use here???
A return type NodeIndex did not work as well. The (partial) compile error message:
...
error[E0308]: arguments to this function are incorrect
--> src\main.rs:17:16
|
17 | self.g.update_edge(a, b, ());
| ^^^^^^^^^^^
|
note: expected struct `NodeIndex`, found `u32`
--> src\main.rs:17:28
|
17 | self.g.update_edge(a, b, ());
| ^
= note: expected struct `NodeIndex`
found type `u32`
...
What I am doing wrong here?
You're importing petgraph::adj::NodeIndex
, which is an alias for u32
, but what you need to import is petgraph::graph::NodeIndex
, which is a different struct.