E4007
E4007 — A value moved while a borrow of it is still used afterwards:let r = &a; let b = a;followed by a use ofr. The borrow would point at a value that has moved away.
What the compiler reports
Error[E4007] at {{.*}}method_returning_a_reference_in_a_struct_keeps_its_argument_borrowed.vx:[[@LINE+1]]:11: `b` is moved 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.view(&b)` returns a struct holding `&b`, so `b` stays borrowed while `r` is used, and
// moving `b` is refused.
import std::vec;
struct N {
v : Vec<i32>,
}
struct R {
r : &N,
}
impl N {
fn view(self : &N, b : &N) -> R {
return R {
r : b
};
}
}
fn main() -> i32 {
let a = N {
v : Vec<i32>::new()
};
let b = N {
v : Vec<i32>::new()
};
let r = a.view(&b);
let c = b;
return (r.r.v.len() + c.v.len()) as i32;
}
From tests/frontend/fail/method_returning_a_reference_in_a_struct_keeps_its_argument_borrowed.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.
E4006An assignment through a shared reference:
*r = v, r.f = v or r[i] = v where r is a &T. A shared reference only reads; writing needs a &mut T. The same for a *const T pointer and for a view of memory made from one: a write, a &mut borrow or a &mut self call through it. Writing needs a *mut T.
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. A match on a reference names parts of the value behind it, so match r { Holder::Full(n) => n } cannot move n either. Through a raw pointer, let b = *p; and let b = p[i]; are refused when the value has something to drop, since its owner drops it too. Only an unsafe fn such as core::ptr::read(p) may take it out.