gpt4 book ai didi

rust - 为什么 String::from(*d) 在 &&str 上给出的结果与 *d.to_string() 不同?

转载 作者:行者123 更新时间:2023-11-29 08:04:57 25 4
gpt4 key购买 nike

我有点困惑为什么取消引用 &&str 在第二种情况下似乎不起作用:

use std::collections::HashSet;

fn main() {
let days = vec!["mon", "tue", "wed"];
let mut hs: HashSet<String> = HashSet::new();

for d in &days {
// works
hs.insert(String::from(*d));

// doesn't
hs.insert(*d.to_string());
}
println!("{:#?}", hs);
}

str 确实实现了 ToString 特征,但它仍然给我错误:

error[E0308]: mismatched types
--> src/main.rs:12:19
|
12 | hs.insert(*d.to_string());
| ^^^^^^^^^^^^^^ expected struct `std::string::String`, found str
|
= note: expected type `std::string::String`
found type `str`

我在这里弄错了什么语法?

Rust Playground Link

最佳答案

to_string被称为 d在它被取消引用之前,所以你将取消引用 String ,结果为 str .

改成

hs.insert(d.to_string());

这是有效的,因为 d自动取消引用为 str , 将转换为 String然后。这叫做 Deref coercions .

If you have a type U, and it implements Deref<Target=T>, values of &U will automatically coerce to a &T

...

Deref will also kick in when calling a method

这是 exactly the case here : impl Deref<Target = str> for String .参见 here for an example :

A value of type &&&&&&&&&&&&&&&&Foo can still have methods defined on Foo called, because the compiler will insert as many * operations as necessary to get it right. And since it’s inserting *s, that uses Deref.

example证明了这一点:

struct Foo;

impl Foo {
fn foo(&self) { println!("Foo"); }
}

let f = &&Foo;

// prints "foo"
f.foo();

顺便说一下,

hs.insert((*d).to_string());

还将work , 因为它首先被取消引用为 &str .

关于rust - 为什么 String::from(*d) 在 &&str 上给出的结果与 *d.to_string() 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49059545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com