Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
incertia opened this issue Jul 25, 2021 · 1 comment
Open

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

incertia opened this issue Jul 25, 2021 · 1 comment

Comments

@incertia
Copy link

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.

@SOF3
Copy link

SOF3 commented Aug 3, 2021

How does this deal with other receiver types, like &mut self and self and Box<Self>?

Btw this is done explicitly for Read and Write on all &Mut references.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants