Reference &&;str.to_owned()不';不会产生字符串
我有以下代码:Reference &&;str.to_owned()不';不会产生字符串,reference,rust,Reference,Rust,我有以下代码: use std::collections::HashMap; fn main() { let xs: Vec<&str> = vec!("a", "b", "c", "d"); let ys: Vec<i32> = vec!(1, 2, 3, 4); let mut map: HashMap<String,i32> = HashMap::new(); for (x,y) in xs.iter().zip
use std::collections::HashMap;
fn main() {
let xs: Vec<&str> = vec!("a", "b", "c", "d");
let ys: Vec<i32> = vec!(1, 2, 3, 4);
let mut map: HashMap<String,i32> = HashMap::new();
for (x,y) in xs.iter().zip(ys) {
map.insert(x.to_owned(), y);
}
println!("{:?}", map);
}
使用std::collections::HashMap;
fn main(){
设xs:Vec=Vec!(“a”、“b”、“c”、“d”);
让ys:Vec=Vec!(1,2,3,4);
让mut映射:HashMap=HashMap::new();
对于xs.iter().zip(ys)中的(x,y){
map.insert(x.to_owned(),y);
}
println!(“{:?}”,map);
}
这会导致错误:
<anon>:8:20: 8:32 error: mismatched types:
expected `collections::string::String`,
found `&str`
(expected struct `collections::string::String`,
found &-ptr) [E0308]
<anon>:8 map.insert(x.to_owned(), y);
:8:20:8:32错误:不匹配的类型:
应为“集合::字符串::字符串”,
找到`&str`
(应为结构`collections::string::string`,
找到和-ptr)[E0308]
:8映射插入(x.到所拥有的(),y);
但这对我来说毫无意义<此时,code>x应该是&&str
。那么,为什么&&str.to_owned()
在这一点上没有像x.to_string()
那样自动地Deref
?(为什么x.to_拥有()
a&str
?)
我知道我可以通过使用
x.to_string()
,或者xs.into_iter()
来解决这个问题。因为ToOwned
是为T实现的,其中T:Clone
,而Clone
是为&T实现的。当T
和&T
都可用时,您需要大致了解&self
上的模式匹配是如何工作的。使用伪语法进行解释
str→ 字符串
str
不匹配&self
&str
(自动引用)将&self
与self==str
因此,ToOwned
开始生效
&str→ 字符串
&str
将&self
与self==str
因此,ToOwned
开始生效
&&str→ &str
&&str
将&self
与self==&str
因此,ToOwned
开始生效
请注意,在这种情况下,auto-deref永远不会启动,因为&T
在T
可能的情况下将始终匹配,这将稍微降低复杂性。还要注意的是,auto-ref只起作用一次(并且对于每个auto-deref'd类型起作用一次)
抄袭
算法的核心是:
- 对于每个
U
(即,设置U=T
,然后设置U=*T
,…)
- 如果有一种方法
bar
,其中接收器类型(方法中的self
类型)与U
完全匹配,则使用它()
- 否则,添加一个自动引用(获取接收器的
&
或&mut
),如果某个方法的接收器匹配&U
,则使用它()
FWIW,.into()
通常比.to_owned()
漂亮(特别是当类型是隐含的时;即使不是隐含的时也经常如此)。不过,您仍然需要手动取消引用。这些工作:map.insert((**x).to_owned(),y)代码>和map.insert((*x).to_-owned(),y)代码>。我认为这与锈蚀在某些情况下不能插入多个*
有关,但我不记得什么时候了。