Quantcast
Channel: Linux.org.ru: Форум (тех. форум)
Viewing all articles
Browse latest Browse all 74609

Fighting the borrow checker: обращение к объекту в аргументах при вызове метода из него же

$
0
0
struct Foo;

impl Foo {
    fn get(&self) -> usize {
        42
    }
    
    fn set(&mut self, b: usize) {
    }
}

fn main() {
    let mut f = Foo;
    
    f.set(f.get());
}

results in


<anon>:15:11: 15:12 error: cannot borrow `f` as immutable because it is also borrowed as mutable [E0502]
<anon>:15     f.set(f.get());
                    ^
<anon>:15:5: 15:6 note: previous borrow of `f` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `f` until the borrow ends
<anon>:15     f.set(f.get());
              ^
<anon>:15:19: 15:19 note: previous borrow ends here
<anon>:15     f.set(f.get());
                           ^
error: aborting due to previous error
playpen: application terminated with error code 101

Почему? Здесь всё верно, иммутабельное заимствование f при вызове get() кончается до вызова set().

 


Viewing all articles
Browse latest Browse all 74609