下面的代码中的代码块1
和代码块2
都可以工作,但我不知道为什么。
Some(&number)
和 Some(number)
之间有什么区别?
use std::collections::HashMap;
fn call(number: &str) -> &str {
match number {
"798-1364" => "We're sorry, please hang up and try again.",
"645-7689" => "Hello, what can I get for you today?",
_ => "Hi! Who is this again?"
}
}
fn main() {
let mut contacts = HashMap::new();
contacts.insert("Daniel", "798-1364");
//====== code block 1
match contacts.get(&"Daniel") {
Some(&number) => println!("Calling Daniel: {}", call(&number)),
_ => println!("Don't have Daniel's number."),
}
//====== code block 2, without '&'
match contacts.get("Daniel") {
Some(number) => println!("Calling Daniel: {}", call(number)),
_ => println!("Don't have Daniel's number."),
}
}
最佳答案
在 contacts.get("Daniel")
中,参数类型为 &str
。
在 contacts.get(&"Daniel")
中,参数类型为 &&str
。
HashMap
的 get()方法实现如下:
pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
self.base.get(k)
}
当您传递 &&str
时,Rust 编译器会自动将 &&str
解引用为 &str
。因此,您的两个版本本质上是等效的。
在你的比赛
ARM 中:
Some(&number)
number
的类型是&str
,Some(number)
number
的类型是&&str
。
同样,由于 Rust 的自动取消引用规则,两者本质上是相同的。
请注意,如果您编写了 Some(&&number)
,则 number
的类型将是 str
并且无法编译消息:
the size for values of type `str` cannot be known at compilation time
但是当您有 &&T
甚至 &&&&&T
时,就如同您有 &T
一样。
关于rust - Some(v) 和 Some(&v) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76277559/