Why is String::find not a method on &str?

时间:2016-10-09 15:54:06

标签: string rust slice

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?

3 个答案:

答案 0 :(得分:8)

显然,文档让你感到困惑。此方法列在本节下面:

Methods from Deref<Target=str>

因此String甚至没有实现,但实际上只是for &str

答案 1 :(得分:5)

实际上它只适用于String,因为它Derefstr

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

相关问题