-
Is it possible to override
operator[]
in rust? -
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 ofoperator.
which let's us access wrapped-object fields via a dot (.
):let b = Box::new(A { field: 5u64 }); b.field; // <------ this
-
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? SoRust
has a thing to blame for too?
Yes - see std::ops::Index and IndexMut
traits.[quote="grubber, post:1, topic:11502"]
How can I implement automatic dereference in a same way the Box does?
[/quote]
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 impl
ementing special traits from the std::ops
module.
- As others have mentioned, implement
Index
(foroperator [] const
) andIndexMut
(foroperator []
). Also, we usually call them just "stuff
operator", not "operator stuff
". - 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 theDeref
andDerefMut
traits. Once(*b).field
works,b.field
will also work. Here's how the standard shared pointer type (Rc
) implements it. - 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.