Skip to content

Implementing Deref and DerefMut for the same type makes it impossible to call &self methods through immutable refs of that type #16099

Closed
@reem

Description

@reem

Code:

struct Ref<T> {
    inner: T
}

impl<T> Deref<T> for Ref<T> {
    fn deref(&self) -> &T {
        &self.inner
    }
}

impl<T> DerefMut<T> for Ref<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.inner
    }
}

trait ImmutableRefTrait { fn immutable_borrow_method(&self) { () } }
trait MutableRefTrait { fn mutable_borrow_method(&mut self) { () } }

impl ImmutableRefTrait for uint {}
impl MutableRefTrait for uint {}

fn main() {
    let a = Ref { inner: 7u };
    a.immutable_borrow_method();
}

Error:

test.rs:28:5: 28:6 error: cannot borrow immutable local variable `a` as mutable
test.rs:28     a.immutable_borrow_method();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions