考虑以下代码:
let s = String::from("hello");
let mut r = String::new();
for c in s.chars() {
r.push(c);
}
chars
是&str
的方法,为什么String
可以调用呢?我想它与强制转换
有关,但我不完全理解这种隐式转换。
最佳答案
这个问题实际上涵盖了这一点: What are Rust's exact auto-dereferencing rules? .该答案包含很多内容,因此我会尝试将其应用到您的问题中。
引用huon的回答:
The core of the algorithm is:
- For each "dereference step"
U
(that is, setU = T
and thenU = *T
, ...)
- if there's a method
bar
where the receiver type (the type ofself
in the method) matchesU
exactly , use it (a "by value method")- otherwise, add one auto-ref (take
&
or&mut
of the receiver), and, if some method's receiver matches&U
, use it (an "autorefd method")
关键在于“解引用步骤”:U = *T
表示 let u = Deref::deref(t);
, 其中u: U
, t: T
.我们一直这样做,直到无法再取消引用某些内容。
按照该算法调用 s.chars()
从你的代码:
- 第一个取消引用步骤(不取消引用):
- 你能打给
String::chars(s)
吗? 没有。 - 那
&String
呢?或&mut String
? 没有。
- 你能打给
- 第二个取消引用步骤:
<String as Deref>::Target = str
, 所以我们正在寻找str
的方法.let c: str = *s
(假设允许此 DST 类型);- 你能打给
str::chars(c)
吗? 没有。 - 你能打给
str::chars(&c)
吗? 是的!
- 你能打给
关于string - 为什么 String 在 Rust 中隐式转换为 &str?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58023943/