Static call of non-static methods

For various reasons I like calling regular methods as if they were static, e.g., not using the dot notation. (For example, Vec::len( &v ) instead of v.len().) I can always do this with my own methods; however, with some methods that belong to the standard library I cannot do it for some reason. For example, Vec::binary_search( &v, &t ) does not compile ("no function or associated item named binary_search found for struct std::vec::Vec<_> in the current scope"), even when v.binary_search( &t ) does. Why is that?

Upvotes: 2

Views: 162

Answers (2)

kmdreko
kmdreko

Reputation: 60082

binary_search isn't implemented in Vec. The call v.binary_search(...) works because of the Deref<Target=[T]> and binary_search is implemented on [T].

Here's how make it work as an associated function.

<[_]>::binary_search(&v, &t);

Upvotes: 1

Masklinn
Masklinn

Reputation: 42302

That is because binary_search is a method of slices, not of Vec.

It is available on Vec because Vec derefs to slice, and method calls auto-deref (that's also why you can call methods of T on a Box<T> or an &T, despite those methods not being implemented on Box or references).

Upvotes: 2

Related Questions