How do I import the implementation of a trait in a given crate?

I'm using petgraph. I have a NodeIndex and I want to access to the data associated to the node.
Index<NodeIndex<Ix>> is implemented for Graph.


I thought I would be able to do:

let my_graph: UnGraph<GraphNodeData, GraphEdgeData> = /* ... */;
let my_index: NodeIndex = /* ... */;

let data: GraphNodeData = my_graph[my_index];

But I got the following error:

error[E0608]: cannot index into a value of type `&local_graph::LocalGraph`

It look like I need to import a trait. To get some help from the compiler I changed the code to:

let data = my_graph.index(my_index);

And got the following error:

error[E0599]: no method named `index` found for reference `&local_graph::LocalGraph` in the current scope
   --> lib/tour_generation/src/local_graph.rs:128:14
    |
128 |         my_graph.index(my_index)
    |                   ^^^^^ method not found in `&local_graph::LocalGraph`
    |
    = help: items from traits can only be used if the trait is implemented and in scope
    = note: the following traits define an item `index`, perhaps you need to implement one of them:
            candidate #1: `std::ops::Index`
            candidate #2: `std::slice::SliceIndex`
            candidate #3: `nalgebra::base::indexing::MatrixIndex`
            candidate #4: `petgraph::graph_impl::IndexType`
            candidate #5: `petgraph::graph_impl::GraphIndex`
            candidate #6: `object::read::traits::ObjectSection`

I took a look at the implementation of the trait Index<NodeIndex<_>> for Graph<...>, it was done in the graph_impl module that isn't re-exported publicly. Does this means that I can't use my_graph[my_index]?

It is indeed implemented for Graph, however you are using it on LocalGraph.

Pffff, you are right. I forgot to do local_graph.0.index(...). I feel a bit stupid!

Everybody makes mistakes. No need to feel bad about it.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.