Reputation: 16705
Looking at the Rc interface I found that the Rc
struct has methods but they are defined without self
so they are static but nothing actually prevents them to be usual object methods. The question is why they are defined so? Why, for example, the Rc::weak_count is defined in the form:
fn weak_count(this: &Rc<T>) -> usize
instead of:
fn weak_count(&self) -> usize
Upvotes: 3
Views: 418
Reputation: 8956
It is to prevent shadowing methods that would otherwise be visible through the Deref
and DerefMut
implementations of Rc
. To quote the documentation of Rc
:
The inherent methods of
Rc
are all associated functions, which means that you have to call them as e.g.Rc::get_mut(&mut value)
instead ofvalue.get_mut()
. This avoids conflicts with methods of the inner typeT
.
For example, if you have Rc<Foo>
where Foo
defines its own method called weak_count
, using a static method would allow the user to write foo.weak_count(…)
to call Foo::weak_count
and Rc::weak_count(&foo)
to call Rc::weak_count
.
(For this reason, adding an intrinsic method to a type that defines Deref
/ DerefMut
will break backward compatibiltiy).
Upvotes: 9