考虑以下代码:
let s = String::from("hello");
let mut r = String::new();
for c in s.chars() {
r.push(c);
}
As chars
的方法是&str
, 为什么可以String
叫它?我想这与coercion
,但我不完全理解这种隐式转换。
这个问题实际上涵盖了这一点:Rust 的确切自动解除引用规则是什么? https://stackoverflow.com/questions/28519997/what-are-rusts-exact-auto-dereferencing-rules。这个答案涉及很多内容,所以我会尝试将其应用于您的问题。
引用huon的回答:
该算法的核心是:
- For each "dereference step" https://github.com/rust-lang/rust/blob/b6d91a2bdac45cd919497a24207fab843124d4ba/src/librustc_typeck/check/method/probe.rs#L166-L196
U
(that is, set U = T
and then U = *T
, ...)
- 如果有一个方法
bar
其中接收器类型(类型self
在方法中)匹配U
确切地说,使用它(“按值方法” https://github.com/rust-lang/rust/blob/b6d91a2bdac45cd919497a24207fab843124d4ba/src/librustc_typeck/check/method/probe.rs#L793)
- 否则,添加一个自动引用(采取
&
or &mut
接收者),并且,如果某些方法的接收者匹配&U
, 用它 (“autorefd 方法” https://github.com/rust-lang/rust/blob/b6d91a2bdac45cd919497a24207fab843124d4ba/src/librustc_typeck/check/method/probe.rs#L798)
关键在于“取消引用步骤”:U = *T
means let u = Deref::deref(t);
, where u: U
, t: T
。我们一直这样做,直到某些东西不能再被取消引用为止。
按照该算法进行调用s.chars()
从你的代码:
- First dereference step (no deref):
- 你可以打电话吗
String::chars(s)
? No.
- 关于什么
&String
or &mut String
? No.
- Second dereference step:
<String as Deref>::Target = str
, so we are looking for methods of str
. let c: str = *s
(assuming this DST type was allowed);
- 你可以打电话吗
str::chars(c)
? No.
- 你可以打电话吗
str::chars(&c)
? Yes!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)