Few easy rust questions

  1. Is it possible to override operator[] in rust?

  2. How can I implement automatic dereference in a same way the Box does? Let’s say I want to create new shared pointer type for learning purposes. To be more detailed, I wanna know how to implement this kind of operator. which let’s us access wrapped-object fields via a dot (.):

     let b = Box::new(A { field: 5u64 });
     b.field; // <------ this
  3. Why is it bad for C++ to have “a lot of templates which inflate the object code” while Rust uses generics as much as possible? So Rust has a thing to blame for too?

  1. You can override the operator[] by implementing either the IndexMut or Index trait. If you implement IndexMut, you also get Index. The examples in the documentation are useful.


Yes - see std::ops::Index and IndexMut traits.[quote=“vityafx, post:1, topic:11502”]
How can I implement automatic dereference in a same way the Box does?

See std::ops::Deref

Not sure I’d call it “bad”, but I know what you’re getting at. Yes, Rust would generally have the same issue. There are ways to use dynamic dispatch instead of monomorphized generic calls, and ways to restrict combinatorial expansions of generic code (e.g. main entry point fn takes a generic type, but delegates to a non-generic fn using some non-generic bits of data from the generic arguments).


Implementing (overloading) operators in Rust is done by implementing special traits from the std::ops module.

  1. As others have mentioned, implement Index (for operator [] const) and IndexMut (for operator []). Also, we usually call them just "stuff operator", not “operator stuff”.
  2. You don’t have to implement the automatic part of it (auto dereference), but you have to implement the dereference itself. In C++ you call that operator *, in Rust it’s the Deref and DerefMut traits. Once (*b).field works, b.field will also work. Here’s how the standard shared pointer type (Rc) implements it.
  3. Not sure where that’s coming from. Rust and C++ both do monomorphization and you can use the same techniques (virtual methods in C++ ≈ trait objects in Rust) to avoid it.


And in fact, trait objects are better (in this one sense) than virtual functions in C++ because the vtbl pointer is part of the reference and not the underlying type; you don’t pay the storage cost if you don’t end up using it.