Repository navigation
Description
We've run into an issue where we have a type that implements both Index<&str> and IndexMut<&str>. Passing an index value of &String causes rustc to choose Index instead of IndexMut, even if a mutable reference is required. If we first call String::as_str and use that as the index, IndexMut is chosen, as expected.
Example repro by @idubrov (see https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9f0e5d703465d4b87218cac8b1eea608):
struct Indexable;
impl Indexable {
fn boo(&mut self) {
}
}
impl std::ops::Index<&str> for Indexable {
type Output = Indexable;
fn index(&self, field: &str) -> &Indexable {
self
}
}
impl std::ops::IndexMut<&str> for Indexable {
fn index_mut(&mut self, field: &str) -> &mut Indexable {
self
}
}
fn main() {
let mut v = Indexable;
let field = "hello".to_string();
// Works
v[field.as_str()].boo();
// Doesn't work
v[&field].boo();
}I expected to see this happen: v[&field] should invoke IndexMut on v since boo() expects a mutable reference.
Instead, this happened: v[&field] invoked Index and complained that IndexMut isn't implemented even though it is:
error[E0596]: cannot borrow data in an index of `Indexable` as mutable
--> src/main.rs:30:5
|
30 | v[&field].boo();
| ^^^^^^^^^ cannot borrow as mutable
|
= help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `Indexable`
Meta
This is reproducible on stable Rust 1.41.0 and 1.43.0 and 1.45.0-nightly (2020-05-06 1836e3b42a5b2f37fd79).
cc: @estebank
Activity
estebank commentedon May 10, 2020
I have a hacky solution to this in #72068. Looking this code up in godbolt I can reproduce it all the way to 1.0, earlier versions giving a type error (
&strvs&String), then an ICE in the 1.2x (that I was causing during my experiments to fix this:error: internal compiler error: re-trying op failed) and finally the current error. The problem is caused (somehow) inconvert_place_op_to_mutableslightly differing fromtry_index_step, but haven't figured how to fix that underlying difference.timotree3 commentedon May 10, 2020
In case this helps to find the root problem, #65682 gives a similar error: "
IndexMutis not implemented" even though it really is.estebank commentedon May 10, 2020
It seems closely related but #72068 sadly doesn't change the behavior on that ticket. I'll take a look at it though.
Rollup merge of rust-lang#72068 - estebank:mut-deref-hack, r=oli-obk