Rust 将hashmap从引用修改为值的最佳方法 使用std::collections::{HashMap,HashSet}; 使用std::hash::{hash}; fn测试(数据:&mut哈希映射){ 匹配数据。获取(“foo”){ 无=>返回, 一些(xs)=>{ 设xs:Vec=xs.iter().map(|x | x.to_owned()).collect(); //如何在这里放置'data',以便我可以借用'data'。 对于x-in-xs{ //发生可变借用,因为以前的“数据”仍在作用域中。 数据删除(&x); } } } }
上面的代码不起作用,因为当上一次借用仍在范围内时,我可以再次修改借用的Rust 将hashmap从引用修改为值的最佳方法 使用std::collections::{HashMap,HashSet}; 使用std::hash::{hash}; fn测试(数据:&mut哈希映射){ 匹配数据。获取(“foo”){ 无=>返回, 一些(xs)=>{ 设xs:Vec=xs.iter().map(|x | x.to_owned()).collect(); //如何在这里放置'data',以便我可以借用'data'。 对于x-in-xs{ //发生可变借用,因为以前的“数据”仍在作用域中。 数据删除(&x); } } } },rust,Rust,上面的代码不起作用,因为当上一次借用仍在范围内时,我可以再次修改借用的数据。然而,我找不到一个简单的方法来解除先前借款的约束 还有,有没有更好的方法来复制xs,这样我可以在迭代hashmap时修改它。您非常接近解决方案。拥有独立向量后,您可以将其移出映射范围: use std::collections::{HashMap, HashSet}; use std::hash::{Hash}; fn test(data: &mut HashMap<String, HashSet<
数据。然而,我找不到一个简单的方法来解除先前借款的约束
还有,有没有更好的方法来复制xs
,这样我可以在迭代hashmap时修改它。您非常接近解决方案。拥有独立向量后,您可以将其移出映射范围:
use std::collections::{HashMap, HashSet};
use std::hash::{Hash};
fn test(data: &mut HashMap<String, HashSet<String>>) {
match data.get("foo") {
None => return,
Some(xs) => {
let xs: Vec<String> = xs.iter().map(|x| x.to_owned()).collect();
// How to drop `data` here so that I can borrow `data`.
for x in xs {
// Mutable borrow occurs, because previous `data` is still in scope.
data.remove(&x);
}
}
}
}
使用std::collections::{HashMap,HashSet};
fn测试(数据:&mut哈希映射){
让xs:Vec=匹配data.get(“foo”){
无=>返回,
一些(xs)=>{
iter().map(| x | x.to|u owned()).collect()
}
};
对于x-in-xs{
数据删除(&x);
}
}
use std::collections::{HashMap, HashSet};
fn test(data: &mut HashMap<String, HashSet<String>>) {
let xs: Vec<String> = match data.get("foo") {
None => return,
Some(xs) => {
xs.iter().map(|x| x.to_owned()).collect()
}
};
for x in xs {
data.remove(&x);
}
}