You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
check: a match on *v.get_ref(0) gets E4003 in its arms, and a match on keep(&mut h, v.get_ref(0)) lets v change while h points into it #4412
Error[E4003] at match_number.vx:8:9: Cannot borrow 'v' as mutable because it is also borrowed as immutable.
The tested value is an i64, so it holds no borrow of v when an arm runs. Rust accepts this program.
match *v.get_ref(0) > 0i64 { true => { v.push(6i64); } false => {} } gets the same error.
let first = *v.get_ref(0); match first { 5i64 => { v.push(6i64); } _ => {} } compiles and prints 2.
#4401 is the same problem for if and while. Its fix in #4409 does not change match, and this program gets the same error on that branch. The arms of a match can use a reference that the tested value holds, as in match get(&s) { Held::R(r) => { .. } }. So the borrows can end only when the tested value cannot hold a reference, as a number or a bool cannot.
The second problem: a call in the tested value stores a reference
import std::vec;
struct Holder {
r : &i64,
}
fn keep(h : &mut Holder, x : &i64) -> bool {
h.r = x;
return true;
}
fn main() -> i32 {
let mut v = Vec<i64>::new();
v.push(5i64);
let zero = 0i64;
let mut h = Holder {
r : &zero
};
match keep(&mut h, v.get_ref(0)) {
true => {}
false => {}
}
for i in 0..100000 {
v.push(i as i64);
}
println!("{}", *h.r);
return 0;
}
keep stores a reference to the first element of v in h. The pushes move the elements of v, so h.r then points at freed memory.
On main (114d88c) this program compiles, with both code generators. It printed 96520299776448 in one run and 95080637823424 in another run. The checker must report E4003 at the push. It does so when the call is a statement, as in keep(&mut h, v.get_ref(0)); v.push(6i64);.
check_escape_in_calls (src/hir/check/escape.rs) gives a stored borrow to the variable that the &mut argument reaches. It does not look at the value that a match tests. #4409 adds this check for the condition of an if, in check_frame_escape_of_a_condition. The value that a match tests probably needs the same check, after check_head_of_branches in src/hir/check/control.rs.
Activity