Skip to content

Allow the trait checker to attempt Deref before giving up #3155

@incertia

Description

@incertia

Fairly self explanatory but it could be a partial solution to #2393 before it is implemented in the rust compiler

Suppose you have some code

use std::ops::Deref;

trait Foo { fn foo(&self); }

struct Bar { }
impl Foo for Bar {
  fn foo(&self) { }
}

fn baz<T: Foo> (_: &T) { }

struct WrapBar { wbar: Bar }

impl Deref for WrapBar {
  type Target = Bar;
  fn deref(&self) -> &Self::Target { &self.wbar }
}

fn main() {
  let b = WrapBar { wbar: Bar {} };
  // explicit call via &Bar
  &b.wbar.foo();
  // implicit Deref to &Bar before call, hooray https://doc.rust-lang.org/reference/expressions/method-call-expr.html
  &b.foo();
  // succeeds because WrapBar can be Deref'd to Bar because we are aware of baz::<Bar> having the signature &Bar -> ()
  baz::<Bar>(&b);
  // fails because WrapBar does not implement Foo because baz has signature &(T: Foo) -> ()
  // baz(&b);
}

Maybe we can amend #241 so that the compiler tries Deref coercion for function arguments with unsolved traits as well.

If this is a dumb idea then feel free to just close this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions