Open
Description
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).
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.