Why is this borrow still “active”?

13

This is a simplified example of something I've encountered:

trait Bla<'a> {
    fn create(a: &'a Foo) -> Self;
    fn consume(self) -> u8;
}

struct Foo;
impl Foo {
    fn take(&mut self, u: u8) {}
}

struct Bar {
    foo: Foo,
}

impl Bar {
    fn foobar<'a, 'b, B: Bla<'b>>(&'a mut self)
    where 'a: 'b {
        let u = {
            // immutable borrow occurs here
            // type annotation requires that `self.foo` is borrowed for `'b`
            let foo: &'b Foo = &self.foo;
            let b = B::create(foo);
            b.consume()
        };

        // error[E0502]: cannot borrow `self.foo` as mutable because it is also borrowed as immutable
        self.foo.take(u);
    }
}

Why is self.foo still considered to be borrowed even after exiting the block it was borrowed on, with everything that used the borrow also dropped?

Share
Improve this question

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue