Closed
Description
use std::ops::{Index, IndexMut};
struct S;
impl S { fn foo(&self) -> i32 { 0 } }
impl Index<usize> for S {
type Output = S;
fn index(&self, _: usize) -> &S { self }
}
impl IndexMut<usize> for S {
fn index_mut(&mut self, _: usize) -> &mut S { self }
}
fn main() {
let s = S;
let _ = &mut s.foo(); // OK
let _ = &mut (&s[0]).foo(); // OK
let _ = &mut s[0].foo(); // error: cannot borrow immutable local variable `s` as mutable
}
The whole example compiles it the IndexMut
implementation is removed.
Activity
gwillen commentedon Dec 9, 2015
I'm also running into something that appears to be this issue. I'm indexing a Vec, so the implementation of IndexMut is not under my control. I can try to make a reduced example using Vec if it would be helpful. EDIT: oh, it seems that 29869 already contains such an example.
PeterHatch commentedon Oct 12, 2017
Just wanted to note that I encountered this bug.
shepmaster commentedon Oct 25, 2018
This came up on Stack Overflow. A simplified example:
Workarounds include:
Using extra braces:
Calling
Index::index
explicitly:Calling
RefCell::borrow
explicitly:jackh726 commentedon Jan 29, 2022
This compiles now. Marking as needs-test (unsure if there is one that covers this already)
9 remaining items