Skip to content

IndexMut incorrectly chosen instead of Index #28935

Closed
@wthrowe

Description

@wthrowe
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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceA-trait-systemArea: Trait systemC-bugCategory: This is a bug.E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.T-langRelevant to the language 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