I have a Vec
of optional HashSet
s. If the slot is None
, I want to allocate a HashSet
and store it in the Vec
.
In both cases, I want to add to the HashSet
.
I understand what the compiler error is complaining about but not what syntax will make the problem go away. The compiler's suggested change also does not compile, as well as any other syntax I try. How do I match the Vec
cell, check if it is None
, allocate a Some<HashSet>
if it is None
or just access the HashSet
if it does exist and in both cases add in a new integer to the set?
THE CODE:
use std::collections::HashSet;
use std::collections::BTreeSet;
use std::iter::FromIterator;
use maplit;
pub struct Graph {
outgoing_edges : Vec<Option<HashSet<usize>>>,
incoming_edges : Vec<Option<HashSet<usize>>>
}
impl Graph {
pub fn new(node_count : usize) -> Self {
Graph {
outgoing_edges : vec!(None; node_count),
incoming_edges : vec!(None; node_count)
}
}
/// Add a directional edge that starts at `from_node` and points to `to_node`.
pub fn add_edge(&mut self, from_node : usize, to_node : usize) {
match &self.outgoing_edges[from_node] {
Some(mut set) => { set.insert(to_node); () },
None => { self.outgoing_edges[from_node] = Some(hashset!{ to_node }); () }
}
match &self.incoming_edges[to_node] {
Some(mut set) => { set.insert(from_node); () },
None => { self.incoming_edges[to_node] = Some(hashset!{ from_node }); () }
}
}
}
THE ERROR:
(Line numbers are from my original file, not the short code snippet. The error message is from before I added the ampersand to borrow, as shown above, but that code change didn't work.)
error[E0507]: cannot move out of index of `std::vec::Vec<std::option::Option<std::collections::HashSet<usize>>>`
--> src\graph\mod.rs:46:15
|
46 | match self.outgoing_edges[from_node] {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider borrowing here: `&self.outgoing_edges[from_node]`
47 | Some(mut set) => { set.insert(to_node); () },
| -------
| |
| data moved here
| move occurs because `set` has type `std::collections::HashSet<usize>`, which does not implement the `Copy` trait