How to get mutable reference from a `Range`?

I have a ordered map, and I'm trying to find the "closest" item from a given key, here's my code:

    let mut ordered_tree = BTreeMap::new();
    ordered_tree.insert(1, Foo::new(1));
    ordered_tree.insert(2, Foo::new(2));
    ordered_tree.insert(4, Foo::new(3));

    // let foo = ordered_tree.get_mut(&1).unwrap();

    let (index, foo) = ordered_tree.range(..3).next_back().unwrap();
    foo.i = 42; // won't comiple, foo is not mutable

but in this case, range returns immutable references, I cannot do mutable stuff on it.

Since the range return a map entry of key/value, I can take a mutable reference by using ordered_tree.get_mut(&index.clone()).unwrap(); to retrieve again, but it will cause another log(n) time.

Anyway to do that safely?

Is there any reason why you aren't simply using range_mut()?


I don't know why my IDE won't show range_mut when I typing, and I check this by mistake :rofl:

Instead of relying on IDEs (which usually come up with inexact, incomplete, lacking, or even wrong suggestions), it's helpful to get acquainted with the idioms of the standard library. For immutable getters, there's generally (but not always) a mutable counterpart, named identically but with a _mut suffix.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.