Rust HashMap编辑值与Iter生锈
嗨,我有一个这样的函数和一个HashMap,问题是我想编辑HashMap,但我有太多的错误与克隆代码编译,但HashMap的值Rust HashMap编辑值与Iter生锈,rust,rust-piston,Rust,Rust Piston,嗨,我有一个这样的函数和一个HashMap,问题是我想编辑HashMap,但我有太多的错误与克隆代码编译,但HashMap的值 struct片段(HashMap); fn按(&mut self,args:&Button){ 让mut coco=self.0.clone(); 对于coco中的(mut x,y){ 如果让按钮::键盘(键)=参数(&B){ 匹配键{ 键::向下=>x.1-=1, 键::左=>x.0+=1, 键::右=>x.0-=1, _ => { println!(“{:?}”,
struct片段(HashMap);
fn按(&mut self,args:&Button){
让mut coco=self.0.clone();
对于coco中的(mut x,y){
如果让按钮::键盘(键)=参数(&B){
匹配键{
键::向下=>x.1-=1,
键::左=>x.0+=1,
键::右=>x.0-=1,
_ => {
println!(“{:?}”,x);
}
};
}
}
}
这里是完整代码的链接,如果您需要/想要尝试
以及货物的依赖性
[dependencies]
piston_window = "0.93.0"
rand = "0.6.5"
当您将
self.0
克隆到coco
时,您正在使用的for循环如下所示。因此,当您修改x
时,实际上并没有影响coco
中的键,因为您无法在HashMap
中变异键
相反,将for循环的主体包装成一个循环,然后将结果返回到self.0
此外,键的+=
/-=
也会翻转
fn按(&mut self,args:&Button){
让coco=self.0.clone();
self.0=coco
.into_iter()
.map(|(mut x,y)|{
如果让按钮::键盘(键)=参数(&B){
匹配键{
//键::Up=>x.1-=1,
键::向下=>x.1+=1,
键::左=>x.0-=1,
键::右=>x.0+=1,
_ => {
println!(“{:?}”,x);
}
};
}
(x,y)
})
.收集();
}
或者,如果您希望避免预先克隆整个HashMap
,则可以在map()
中使用.iter()
和clone()
fn按(&mut self,args:&Button){
self.0=self
.0
.国际热核实验堆(iter)
.map(|(x和y)|{
设mut x=x.clone();
如果让按钮::键盘(键)=参数(&B){
匹配键{
//键::Up=>x.1-=1,
键::向下=>x.1+=1,
键::左=>x.0-=1,
键::右=>x.0+=1,
_ => {
println!(“{:?}”,x);
}
};
}
(x,y)
})
收集::();
}
或者您可以mem::replace()
和extend()
fn按(&mut self,args:&Button){
让coco=std::mem::replace(&mutself.0,HashMap::new());
self.0.extend(coco.into_iter().map(|(mut x,y)|{
如果让按钮::键盘(键)=参数(&B){
匹配键{
//键::Up=>x.1-=1,
键::向下=>x.1+=1,
键::左=>x.0-=1,
键::右=>x.0+=1,
_ => {
println!(“{:?}”,x);
}
};
}
(x,y)
}));
}
另外,我强烈建议使用以保持代码格式良好,更不用说英文和非英文名称的混合会造成混乱。请注意,修改
HashMap
中的键,使其哈希或eqaulity受到影响是一个逻辑错误。非常感谢您的帮助,我将尝试仅使用英文变量名,并使用rustfmt非常感谢您不需要克隆HashMap
:您可以直接执行self.0=self.0.into_iter().map(…).collect()
@Jmb No您不能使用self.0.into_iter()
,因为您无法移动self.0
。相反,您可以使用iter()
和x.clone()
或mem::replace()
和extend()
(我已经更新了答案,以包含示例)