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?
答案 0 :(得分:8)
答案 1 :(得分:5)
实际上它只适用于String
,因为它Deref
到str
:
Methods from Deref<Target=str>
您在the source for String但未在the source for str
中找到它。
答案 2 :(得分:5)
实际上......你错了:它不是String
方法。
您所关注的是str::find
。
就是这样,Rust文档会自动在String
页面上包含String
实现Deref<Target=str>
为can be seen here的事实所带来的方法。
为什么文档中包含可以在Deref
目标上调用的方法?
因为您实际上可以直接在String
对象上调用它们,因为如果找不到您正在调用的方法,编译器将自动跟随Deref
。