【问题标题】:Why does String implicitly convert to &str in Rust?为什么 String 在 Rust 中隐式转换为 &str?
【发布时间】: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 rust


【解决方案1】:

这个问题实际上涵盖了这一点: What are Rust's exact auto-dereferencing rules?。该答案有很多内容,因此我将尝试将其应用于您的问题。

引用 huon 的回答:

算法的核心是:

  • 对于每个"dereference step"U(即设置U = T,然后设置U = *T,...)
    1. 如果有一个方法bar,其中接收者类型(方法中self的类型)与U完全匹配,使用它(a "by value method"
    2. 否则,添加一个自动引用(以接收者的&&mut),如果某些方法的接收者与&U 匹配,则使用它(an "autorefd method"

关键在于“取消引用步骤”:U = *T 表示let u = Deref::deref(t);,其中u: Ut: T。我们一直这样做,直到无法再取消引用为止。

按照该算法从您的代码中调用s.chars()

  1. 第一个取消引用步骤(无取消引用):
    1. 你能打电话给String::chars(s)吗? 没有。
    2. &String&mut String 怎么样? 没有。
  2. 第二个解引用步骤:<String as Deref>::Target = str,所以我们正在寻找str的方法。 let c: str = *s(假设允许使用此 DST 类型);
    1. 你能打电话给str::chars(c)吗? 没有
    2. 你能打电话给str::chars(&c)吗? 是的!

【讨论】:

    猜你喜欢
    • 2017-05-01
    • 2013-03-01
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多