I need to implement a function similar to the unstable BTreeSet::pop_first()
.
It is not a duplicate of Getting first member of a BTreeSet, since I ask for a way get the first element of a BTreeSet without making a copy.
fn pop<O:Ord>(set: &mut std::collections::BTreeSet<O>) -> O
Based on a previous question (Getting first member of a BTreeSet), I get a compiler error about a mutable use after an inmutable one:
pub fn pop<O:Ord>(set: &mut std::collections::BTreeSet<O>) -> O {
let n = {
let mut start_iter = set.iter();
start_iter.next().unwrap()
};
set.take(n).unwrap()
}
error[E0502]: cannot borrow `*set` as mutable because it is also borrowed as immutable
--> src/main.rs:493:5
|
489 | let mut start_iter = set.iter();
| --- immutable borrow occurs here
...
493 | set.take(n).unwrap()
| ^^^^----^^^
| | |
| | immutable borrow later used by call
| mutable borrow occurs here
If I replace set.iter()
with set.iter().clone()
the code works, but I would like to not make copies of the elements of the set because it will be a costly operation.
How can I implement such a pop
function?
rustc version 1.41.0