string - 为什么 String 在 Rust 中隐式转换为 &str?

标签 string rust

考虑以下代码:

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, set U = T and then U = *T, ...)
    1. if there's a method bar where the receiver type (the type of self in the method) matches U exactly , use it (a "by value method")
    2. 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()从你的代码:

  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)吗? 是的!

关于string - 为什么 String 在 Rust 中隐式转换为 &str?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58023943/

相关文章:

java - 信用卡验证

java - 如何在 Java 中解析字符串并查找 double

python插入字符串中间

websocket - 在 Iron 中使用 rust-websocket

C# 查找数组中只出现一次的单词

string - Go 中长字符串文字的最佳实践

rust - 了解 Rc<RefCell<SomeStruct>> 在 Rust 中的用法

rust - 如何避免此程序的 for 循环和 let 语句

rust - 为什么不能将此迭代器用作flat_map闭包的返回值?

reference - 尝试转移所有权时无法移出借用的内容