E4009
E4009 — An assignment to a variable, or a field or element of it, while a&borrow of it is still used afterwards:let r = &x; x = 2;and then a use ofr. The borrow would see the value change under it.
What the compiler reports
Error[E4009]{{.*}}`b.v` is assigned while it is borrowed
The fragments the test suite holds the compiler to. An ellipsis marks text the test does not constrain; the emitted message also carries a source location.
A program that triggers it
//
// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions.
// See LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//
// A method returning `bool` does not keep its argument borrowed, but a real reference still
// does. `r` borrows `b` and is used after the assignment, so the assignment is refused.
struct Num {
v : i32,
}
impl Num {
fn same_as(self : &Num, other : &Num) -> bool {
return self.v == other.v;
}
}
fn main() -> i32 {
let a = Num {
v : 1i32
};
let mut b = Num {
v : 1i32
};
let r = &b;
let same = a.same_as(&b);
b.v = 2i32;
if same {
return r.v;
}
return 0i32;
}
From tests/frontend/fail/borrow_kept_by_a_reference_next_to_a_bool_result.vx, which asserts this diagnostic on every commit.
Related
Ownership and borrowingThe chapter covering the rule this code enforces.
All diagnosticsEvery code the compiler can emit, grouped by stage.
E4008A value moved out from behind a reference:
let b = *r; where r is a reference to a type that is not Copy. The reference does not own the value, so it cannot give it away; copy or clone it instead.
E4010A change to a variable declared without mut: assigning it, or a field or element of it, borrowing it &mut, or calling a method that takes &mut self on it. Declare it let mut x, or for a parameter mut x : T.