Description
If a type B
implements Deref
to get out &A
, then auto-deref based method resolution of instances of B
will include methods of A
that require &mut self
, even when there is no DerefMut
that would be necessary for such auto-deref to work.
We still reject the code, with the message "cannot borrow immutable borrowed content as mutable"
What I would prefer is for the message to say something like:
error: cannot do mutable borrow via Deref alone
note: would need (at least) impl DerefMut for A
- (i included some weasel language in the above that might be better editted out of a good error report.)
(I think @nikomatsakis is well aware of this problem; he's mentioned the issue about how the auto-deref code needs to use a conservative guess during method resolution and rely on later compiler stages to reject the method lookup.)
Here is an example of code exhibiting the problem playpen:
use std::ops::Deref;
struct A(i32);
struct B(A);
impl A {
fn yow(&mut self) { println!("Hi"); }
}
impl Deref for B {
type Target = A;
fn deref(&self) -> &Self::Target { &self.0 }
}
fn main() {
let mut b = B(A(3));
b.yow();
}
The error message when you run this (on nightly) is:
<anon>:17:5: 17:6 error: cannot borrow immutable borrowed content as mutable
<anon>:17 b.yow();
^
error: aborting due to previous error
This message can be frustrating, especially when the content appears mutable at the point that is highlighted by the span of the error message; after all, I did use let mut b = ...