Skip to content

&mut references located in aliasable memory should be considered frozen #10445

@nikomatsakis

Description

@nikomatsakis

We only permit &mut pointees to be mutated if the &mut is in a unique location (i.e., another &mut, a local variable, etc). Based on this, it is safe to conclude that the memory referenced by an &mut pointer found in an aliasable location is frozen. But the borrow checker considers such memory to be unsafe for use. This is overly conservative and prevents important compositional patterns.

In particular, I should be able to define a type BorrowedMap that looks like this:

struct BorrowedMap<'m,K,V> {
    map: &'m mut HashMap<K,V>
}

and now I should be able to implement the Map<K,V> trait for BorrowedMap:

impl<'m,K,V> Map<K,V> for BorrowedMap<'m,K,V> {
    fn insert(&mut self, key: K, value: V) { self.map.insert(key, value); }
    fn find<'a>(&'a self, key: &K) -> Option<'a V> {
        self.map.find(key) // ERROR
    }
}

However I can't because I get an error at the marked line. This is because self.map is an &mut found inside of an aliasable location (self) and hence it cannot be considered frozen. But why not? Nobody can mutate it, after all.

Note that the maximum lifetime of a freeze would be 'a (which is sufficient for this case).

Nominating.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions