简体   繁体   English

为什么String :: find不是&str的方法?

[英]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? 我错过了为什么会这样,或者只是一次历史性事故?

Apparently, the documentation confused you. 显然,文档困惑了你。 This method is listed under this section: 此方法列在本节下面:

来自Deref <Target = str>的方法

So it is not even implemented for String , but indeed just for &str . 所以它甚至没有为String实现,但实际上只是为了&str

Actually it's only available for String because it Deref s to str : 实际上它只适用于String因为它可以Derefstr

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM