【发布时间】:2019-09-20 07:42:15
【问题描述】:
考虑以下代码:
let s = String::from("hello");
let mut r = String::new();
for c in s.chars() {
r.push(c);
}
既然chars是&str的方法,为什么String可以调用呢?我想它与coercion 有关,但我并不完全理解这种隐式转换。
【问题讨论】:
-
确切的解释在String documentation。
-
@edwardw 我知道它可以将
&String转换为&str,但是这里它没有得到s的引用。 -
@chenzhongpu "在查找方法调用时,接收者可能会被自动取消引用或借用以调用方法。" (doc.rust-lang.org/reference/expressions/method-call-expr.html)
-
另见书中较长的Deref强制解释:doc.rust-lang.org/book/…