[英]Why is String::find not a method on &str?
I recently noticed that String::find
is actually a method on an owned String
. 我最近注意到
String::find
实际上是一个拥有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
). 但我不明白为什么它不仅仅是
&str
的方法,而是在更多的情况下使用它(并且仍然对String
有用)。 Am I missing a reason for why it's like this, or is it just a historical accident? 我错过了为什么会这样,或者只是一次历史性事故?
Actually it's only available for String
because it Deref
s to str
: 实际上它只适用于
String
因为它可以Deref
为str
:
Methods from Deref<Target=str>
You won't find it in the source for String , but in the source for str
. 您不会在String的源代码中找到它,而是在
str
的源代码中找到它。
Actually... you are wrong: it is not a String
method. 实际上......你错了:它不是
String
方法。
What you are looking at is str::find
. 你在看什么是
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 . 事实上,Rust文档会自动在
String
页面上包含String
实现Deref<Target=str>
这一事实所引入的方法, 如此处所示 。
Why does the documentation includes the methods that can be called on the target of Deref
? 为什么文档中包含可以在
Deref
目标上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. 因为您实际上可以直接在
String
对象上调用它们,因为如果找不到您正在调用的方法,编译器将自动跟随Deref
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.