E4007

E4007 — A value moved while a borrow of it is still used afterwards: let r = &a; let b = a; followed by a use of r. 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