Implementing Index trait to return a value that is not a reference

The Index trait is meant to return a borrowed pointer to a member of self (e.g. an item in a Vec). The signature of the index method from the Index trait makes it impractical to implement it to have the behavior you described, as you’d have to store every value returned by index in self and ensure that the pointers remain valid until the MyStruct is dropped.

Leave a Comment