I recently noticed that String::find
is actually a method on an owned String
.
But I can't see why it wouldn't just be a method on &str
instead, making it useful in more cases (and still being just as useful for String
). Am I missing a reason for why it's like this, or is it just a historical accident?
Apparently, the documentation confused you. This method is listed under this section:
So it is not even implemented for String
, but indeed just for &str
.
Actually it's only available for String
because it Deref
s to str
:
Methods from Deref<Target=str>
You won't find it in the source for String , but in the source for str
.
Actually... you are wrong: it is not a String
method.
What you are looking at is str::find
.
It just so happens that the Rust documentation automatically includes on the String
page the methods brought in by the fact that String
implements Deref<Target=str>
as can be seen here .
Why does the documentation includes the methods that can be called on the target of Deref
?
Because you can actually call them directly on a String
object, since the compiler will automatically follow Deref
if it does not find the method you are calling, recursively.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.