Implements SliceIndex for custom type

Hello, I have the following custom type:

#[derive(Debug, Copy, Clone, Hash)]
pub struct NodeId(pub usize);

impl PartialEq for NodeId {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0

impl From<usize> for NodeId {
    fn from(id: usize) -> Self {

impl Eq for NodeId {}

And I would like to use it in a vec like the following:

let id = NodeId(0);
let vec: Vec<Node> = vec![...];
let element = vec[id];
let option_element = vec.get(id);

But I get the following error slice indices are of type "usize" or ranges of "usize", with the following advice

help: the trait std::slice::SliceIndex<[graph_engine::model::node::NodeRef]> is not implemented for graph_engine::model::ids::NodeId

I looked at the documentation and implementing SliceIndex doesn't seems trivial at all...

You have to create a new wrapper vector type as well. You can then implement the Index trait to make the node id and node vector go together.

1 Like

As well as being easier/not involving any unstable traits, this is probably a better idea from an API perspective, as it means you can't accidentally index a normal Vec with a NodeId, and you can't accidentally index a NodeVec with a plain usize.

1 Like

This is still the case if you use nightly and implement SliceIndex<[Node]> for NodeId.

1 Like

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.