rust

Rust version of Python's __getitem__


Python has a special class method __getitem__ that is basically syntactic sugar. For example,

class MyList:
    def __init__(self):
        self.list = []
    def __getitem__(self, key):
        return self.list[key]

will allow you to get elements of MyList objects like this: mylist[2]. I wonder if there is a trait in Rust that does the same kind of thing. Just like the trait Ord in Rust allows you to use >, <, ==.


Solution

  • You can implement Index for your struct, which allows you to use the bracket operators to get an immutable reference to the data.

    If you want mutable access, you also need to implement IndexMut.