Skip to content

Instantly share code, notes, and snippets.

@incertia
Last active July 25, 2021 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save incertia/ff3c8265288407e9535d73d464d77819 to your computer and use it in GitHub Desktop.
Save incertia/ff3c8265288407e9535d73d464d77819 to your computer and use it in GitHub Desktop.
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
&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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment