我有一个集合,它是某个模块中结构中的一个字段。我想从另一个模块更新集合中的所有值。
我写了一些代码来模仿我想要实现的目标。它缩短了一点,但我认为它有所有需要的部分。在此代码中没有包含集合的结构,但想象这是一个返回集合的getter。我在评论中添加了我认为它应该看起来的样子。
pub mod pos {
use std::cmp::{Ordering, PartialEq};
#[derive(PartialOrd, PartialEq, Eq, Hash, Debug, Copy, Clone)]
pub struct Pos {
pub x: i32,
pub y: i32,
}
#[allow(dead_code)]
impl Pos {
pub fn of(x: i32, y: i32) -> Self {
Self { x, y }
}
pub fn offset(&mut self, pos: &Self) -> Self {
self.x += pos.x;
self.y += pos.y;
*self
}
}
impl Ord for Pos {
fn cmp(&self, other: &Self) -> Ordering {
if self.x < other.x {
Ordering::Less
} else if self.eq(other) {
Ordering::Equal
} else {
Ordering::Greater
}
}
}
}
mod test {
use crate::pos::Pos;
use std::collections::BTreeSet;
#[test]
fn test_iterators() {
let mut data_in_some_strct: BTreeSet<Pos> = BTreeSet::new();
data_in_some_strct.insert(Pos::of(1, 1));
data_in_some_strct.insert(Pos::of(2, 2));
data_in_some_strct.insert(Pos::of(3, 3));
data_in_some_strct.insert(Pos::of(4, 4));
// mimic getter call ( get_data(&mut self) -> &BTreeSet<Pos> {...}
// let set = data_in_some_strct; // works, but not a reference
let set = &data_in_some_strct; // doesn't work, How to adjust code to make it work??
data_in_some_strct = set
.into_iter()
.map(|mut p| p.offset(&Pos::of(1, 0)))
.inspect(|p| println!("{:?}", *p))
.collect();
assert_eq!(data_in_some_strct.contains(&Pos::of(2, 1)), true);
assert_eq!(data_in_some_strct.contains(&Pos::of(3, 2)), true);
assert_eq!(data_in_some_strct.contains(&Pos::of(4, 3)), true);
assert_eq!(data_in_some_strct.contains(&Pos::of(5, 4)), true);
}
}
error[E0596]: cannot borrow `*p` as mutable, as it is behind a `&` reference
--> src/lib.rs:56:26
|
56 | .map(|mut p| p.offset(&Pos::of(1, 0)))
| - ^ `p` is a `&` reference, so the data it refers to cannot be borrowed as mutable
| |
| help: consider changing this to be a mutable reference: `&mut pos::Pos`
我设法让它无需借用,但我希望借助它。我想有更多的方法来实现它。欢迎提出帮助我的Rust brain dendrites连接的评论。
您不能改变属于HashSet
或BTreeSet
的项目,因为项目的值决定了它们的存储和访问方式。如果你改变它们,那么,就像Stargateur mentioned一样,你会破坏集合的机制。在HashSet
的情况下,您将更改项的哈希值,该哈希值确定数据的存储位置。在BTreeSet
的情况下,算法基于项目的排序方式。
您可以通过获得所有权来实现,因为您使用了原始集合并生成了一个新的,格式良好的集合。你不能取得借来的价值的所有权,因为这会留下一个悬挂的指针,Rust不会让你这么做。
一种可能的解决方案是暂时用空的替换原始组。然后,您可以获取其内容的所有权,就像在您的工作代码中一样,最后在原始文件上写下新更新的集:
let set = std::mem::replace(&mut data_in_some_strct, BTreeSet::new());
data_in_some_strct = set.into_iter()
.map(|mut p| p.offset(&Pos::of(1,0)))
.inspect(|p| println!("{:?}", *p))
.collect();
BTreeSet
没有实施impl<'a, T> IntoIterator for &'a mut BTreeSet<T>
(这将破坏树)。
你只能使用像IntoIterator
,mut
这样的impl<'a, T> IntoIterator for &'a mut Vec<T>
实现example的类型。