In-place update of slice of mutable refs

⚓ Rust    📅 2025-07-17    👤 surdeus    👁️ 2      

surdeus

So I've got a tree-like datastructure, and I'm traversing a list of items at the same time.

I've reduced the borrowing issue to a tiny example: Playground

enum Node {
    Branch(Vec<Node>),
    Leaf
}

fn go_down_selected_node(many_nodes : &mut [&mut Node], idx: usize) {
    for n in many_nodes {
        let Node::Branch(br) = n else {unreachable!();};
        *n = &mut br[idx];
    }
}

The borrow checker complains (rightfully I believe) that many_nodes should have the type: &'a mut [&'a mut Node] because the list's lifetime latches on to each element due to the mutable iteration, but there should be a way to update every element of a mutable slice that doesn't latch onto the list's lifetime provided that the update of an element doesn't get to look at other elements.

Kind of like:

impl<'c, T> &'c mut [T] {
    pub fn update_with(self, mut f: impl FnMut(&mut T)) {
        // effectively:
        for v in self {
            f(v)
        }
    }
}

Do you know a standard way of doing this, or crates that provide this functionality?

Edit:
an even more compact example illustrating what I'd like to be able to do:

pub fn update_with<'e, T>(slice: &mut [&'e mut T], mut f: impl FnMut(&'e mut T) -> &'e mut T) {
    // explicit lifetime required in the type of `slice`. Lifetime `'e` required
    for v in slice {
        *v = f(*v)
    }
}

1 post - 1 participant

Read full topic

🏷️ rust_feed