Thoughts on proposed View types by @nikomatsakis?

134 points xmBQWugdxjaA 131 comments

@nikomatsakis has written about the possible proposal of View Types, see:

The idea is where today you might have a struct like (copied from the summary post):

struct WidgetFactory {
    counter: usize,
    widgets: Vec<Widget>,
}

impl WidgetFactory {
    fn increment_counter(&mut self) {
        self.counter += 1;
    }
}

Calling increment_counter() will fail when iterating over widgets, due to having to mutably borrow the whole of self in order to mutate the counter field (despite it being a separate field from what we are iterating over).

pub fn count_widgets(&mut self) {
    for widget in &self.widgets {
        if widget.should_be_counted() {
            self.increment_counter();
            // ^ 💥 Can't borrow self as mutable
            //      while iterating over `self.widgets`
        }
    }    
}

View types would address this by allowing you to specify the set of fields you borrow over explicitly:

impl WidgetFactory {
    fn increment_counter(&mut {counter} self) {
        self.counter += 1;
    }
}

So now the increment_counter function would only mutably borrow the counter field itself, and not the whole self.

This is the most common frustration I hit every day working with Rust. AFAIK there isn't an official proposal / RFC yet - but I was wondering what peoples' thoughts are? As for me it'd be a huge improvement over the status quo.

Although the abstract fields syntax in the redux post is a bit more scary than the simple example above (more boilerplate) if it's only necessary where you actually need the view types, then I think it's okay.

It's well worth reading The Borrow Checker Within post as I think every proposal there is great.