简体   繁体   English

为什么将&应用于字符串会返回&str?

[英]Why does applying & to a String return a &str?

In this example code from the Rust documentation : 在这个示例代码中, 来自Rust文档

fn takes_str(s: &str) { }

let s = String::from("Hello");

takes_str(&s);

What exactly is going on behind the scenes that causes &s to become a &str instead of a &String ? 导致&s变成&str而不是&String的幕后到底发生了什么? The documentation seems to suggest that there's some dereferencing going on, but I thought * was for dereferencing, not & ? 该文档似乎表明正在进行一些取消引用,但是我认为*是用于取消引用,而不是&

What's going on here is called deref coercions . 这里发生的事情称为deref强制 These allow references to types that implement the Deref trait to be used in place of references to other types. 这些允许使用对实现Deref特征的类型的引用来代替对其他类型的引用。 As your example shows, &String can be used anywhere a &str is required, because String implements Deref to str . 如您的示例所示, &String可以在需要&str任何地方使用,因为String实现Derefstr Deref

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM