Splitting borrows in The Rustonomicon

Hello,

I am trying to understand the constraints on splitting borrows.

In the following excerpt from Splitting Borrows - The Rustonomicon

it's pretty clearly hopeless for borrowck to understand disjointness in general container types like a tree, especially if distinct keys actually do map to the same value.

  1. Spatial Disjointedness is definitely needed for splitting into a mutable and (mutable|immutable) borrow. However, conceptually is being disjointed a pre-requisite for splitting a container for multiple immutable borrows?
  2. When can distinct keys map to the same value? If keys follow ownership rules then keys should never map to shared resources such that a split borrow violates these rules. An example would help clarify.

Thank you for your time.

I'm not sure what exactly you are asking here. You don't need to split immutable borrows because they are copiable. You can easily have multiple immutable references to the same thing, or to different elements of a collection.

struct BadVec<T>(Vec<T>);

impl<T> Index<usize> for BadVec<T> {
    type Output = T;
    fn index(&self, _ignore: usize) -> &T {
        &self.0[0]
    }
}

impl<T> IndexMut<usize> for BadVec<T> {
    fn index_mut(&mut self, _ignore: usize) -> &mut T {
        &mut self.0[0]
    }
}

No matter what index you specify, the BadVec will always return a (mutable) reference to the first element.

1 Like

Got it! Thank you.

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.