Skip to content

method resolution problem related to Box<dyn Trait> #38425

@whitequark

Description

@whitequark

To reproduce:

use std::ops::{Deref, DerefMut};
use std::borrow::BorrowMut;

pub enum Managed<'a, T: 'a + ?Sized> {
    Borrowed(&'a mut T),
    Owned(Box<BorrowMut<T>>)
}

impl<'a, T: 'a + ?Sized> Deref for Managed<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        match self {
            &Managed::Borrowed(ref value) => value,
            &Managed::Owned(ref value) => value.borrow()
        }
    }
}

impl<'a, T: 'a + ?Sized> DerefMut for Managed<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        match self {
            &mut Managed::Borrowed(ref mut value) => value,
            &mut Managed::Owned(ref mut value) => value.borrow_mut()
        }
    }
}

If you comment the impl DerefMut, everything compiles. If you uncomment it:

error[E0277]: the trait bound `Box<std::borrow::BorrowMut<T> + 'static>: std::borrow::Borrow<T>` is not satisfied
  --> <anon>:24:57
   |
24 |             &mut Managed::Owned(ref mut value) => value.borrow_mut()
   |                                                         ^^^^^^^^^^ trait `Box<std::borrow::BorrowMut<T> + 'static>: std::borrow::Borrow<T>` not satisfied
   |
   = help: the following implementations were found:
   = help:   <Box<T> as std::borrow::Borrow<T>>

which seems clearly nonsensical.

Changing value.borrow_mut() to (**value).borrow_mut() fixes it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-dyn-traitArea: trait objects, vtable layoutA-type-systemArea: Type systemC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types 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