是否有可能得到一个集合的值,并适用于它的一种方法,其只接受self
而不是&self
?从集合中获取价值,而无需使用克隆特质
最小工作实例
我想什么写的是一个类似于:
use std::collections::HashMap;
fn get<B>(key: i32, h: HashMap<i32, Vec<(i32, B)>>) -> i32 where B: Into<i32> {
let v: &Vec<(i32, B)> = h.get(&key).unwrap();
let val: &B = v.first().unwrap().1;
// Do something to be able to call into
// I only need the value as read-only
// Does B have to implement the Clone trait?
return val.into();
}
我在徒劳地试图在这里和那里运球mut
尝试编译后安抚编译器错误错误,但这真是一个傻瓜的差事。
use std::collections::HashMap;
fn get<B>(key: i32, mut h: HashMap<i32, Vec<(i32, B)>>) -> i32 where B: Into<i32> {
let mut v: &Vec<(i32, B)> = h.get_mut(&key).unwrap();
let ref mut val: B = v.first_mut().unwrap().1;
return (*val).into();
}
是这样的事情甚至有可能或确实B
必须实现Clone
特质?
我也试过:
- 不安全
- 原始指针
我还没有尝试:
Box
- 其他防锈构造,我有未遇到, 我提到这一点,明确指出我没有删除任何我知道的方法。
我希望'HashMap'仍然将密钥与它具有的相同向量关联起来。 –
@FilipAllberg A.B.的观点虽然非常重要。通过接受'h:HashMap',你可以将map *的所有权转移给函数*。这个函数对地图的作用基本没有关系,因为没有别的东西能够使用地图。 – Shepmaster
注意到,现在使用'&h'。谢谢! –