Skip to content

Improve help message when using &'a mut &'a T and &'a mut [&'a T] #85723

Open
@robinmoussu

Description

@robinmoussu

This is a follow-up of a discussion I initiated on internals after watching crust of Rust: Subtyping and Variance.

Both &'a mut &'a T and &'a mut [&'a T] are (I think) always a bug in a program, and never what the programmer intended. What he wanted to write was &'a mut &'b T and &'a mut [&'b T] (ie. having two different lifetimes).

playground

Note: &'a mut [&'a T] gives the same error than the following one (see the playground for more details). Using such pattern as an argument to a function, or a the field of a structure is equally buggy.

fn foo<'a>(_: &'a mut &'a str) { }

fn main() {
    let mut x = "test";
    foo(&mut x);
    assert_eq!(x, "test");
}

The current output is:

error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
  --> src/main.rs:15:9
   |
14 |         foo(&mut x);
   |             ------ mutable borrow occurs here
15 |         assert_eq!(x, "test");
   |         ^^^^^^^^^^^^^^^^^^^^^^
   |         |
   |         immutable borrow occurs here
   |         mutable borrow later used here

I think that the output should look something like:

help: it is possible that you want to use two different lifetimes
 5 |  fn foo<'a>(_: &'a mut &'a str) {
   |                 ^^      ^^
help: you may try to introduce a new lifetime
 5 | fn foo<'a1, 'a2>(_: &'a1 mut &'a2 str) {
   |        ^^^  ^^^      ^^^      ^^^
help: You can learn more about variance and lifetimes (todo: put a link)

TL;DR and notes:

  • &'a mut &'a T and &'a mut [&'a T] are valid Rust, but is (IMHO) never what the programmer intended to write
  • While &'a &'a T is also probably buggy, in practice it never cause issue since & doesn’t requires uniqueness for the borrow. This link shouldn’t warn against it.
  • &'a mut S<'a> is valid, this lint shouldn’t warn against it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsA-varianceArea: Variance (https://doc.rust-lang.org/nomicon/subtyping.html)C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions