Method calls on Box objects in Rust automatically dereference the object contained in the Box wrapper.
For example
let my_variable: std::boxed::Box<i32> = std::boxed::Box::new(42);
let my_new_variable = my_variable.ilog2();
This example is contrived. The important concept here is that a function (in this case ilog2) can be called on some type (in this case i32) which is wrapped in a box.
In C++, the dereference and function call operator would be required:
// C++ would require this
my_new_variable = my_variable->ilog2();
My question is the following:
- Does the automatic dereferencing of "boxed" objects prevent functions being called on the
Boxtype itself? Are such function calls implicitly prohibited?
To further elaborate:
The type Box contains a function called leak.
- How would one call the function
leak()on a Box object if method calls implicitly dereference the contents of the box? - If calling a function which is associated with a Box object, on a Box object, "just works", then how would one disambiguate between two function calls which have the same name?(One associated with the
Boxand one associated with the type contained in theBox)
Syntactically:
If Box wraps type T such that we have Box<T>, and Box has a function Box::leak() and T has a function T::leak(), how do we disambiguate between the two function calls?
The details of this can be found in the reference on Method call expressions. The gist of it is the following
That is, if
Box<T>had a method.quack(), andThad a method of the same name, a method call likefoo.quack()wherefoois of typeBox<T>would refer to the implementationBox::quack(); theT::quack()is effectively shadowed. As to your question, this does not prevent theBox-type (or any otherDeref-type) from implementing methods that their inner type also implements, or vice versa.For example:
In almost all cases, this behavior brings convenience to calling methods on any
Tthat is wrapped in a smart-pointer. In order to visually/mentally disambiguate calls to methods onTvs. methods on the smart-pointer itself, smart-pointers usually don't have methods by themselves but only associated functions.Box::leak()is one example, and there are many others, which enforce a syntax likeBox::leak(foo);instead offoo.leak();for visual disambiguity.One example where there is visual/mental ambiguity is the
Cloneimplementation onRc/Arc, where callingfoo.clone()looks like cloning the innerT, while in fact, one is only cloning (increasing the reference count) of the outerRc/Arc.