Reputation: 5566
I want to create Nodes (weights) which contain its own NodeIndex
struct Node {
index: NodeIndex,
...
}
However, in order to get the NodeIndex
, I need to call graph.add_node(node)
which requires a fully constructed Node
.
Is there a way I can accomplish this without having to use Option<NodeIndex>
?
Upvotes: -1
Views: 99
Reputation: 71005
I'm not saying it's a good idea, but NodeIndex
implements Default
, so you can fill it initially with the default value, and once you call add_node()
and get the real index, index the graph with it and overwrite the node data.
Upvotes: 0
Reputation: 5566
I managed to change my design such that this is no longer necessary, and probably for the better.
The point of using petgraph (at least in my case) is to create a graph like structure without having to deal with self-referential types (see this post for more details).
This only works if petgraph's Graph
has (sole?) ownership of the nodes. Once you add your node to the graph via graph.add_node(node)
, it returns you the NodeIndex
which will be your handle towards that node
in the future (think of it as a pointer).
So storing the NodeIndex
inside the Node
makes as much sense as storing the pointer to the object inside the object itself. In my case, it was a symptom of a misuse and misunderstanding of petgraph.
Upvotes: 0