Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created March 26, 2018 06:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rust-play/b8485987c22a1c0b9d20e1c5655c4f1c to your computer and use it in GitHub Desktop.
Save rust-play/b8485987c22a1c0b9d20e1c5655c4f1c to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
trait Foo {
fn method(&self);
}
trait Cast<T> {
fn cast(t: &T) -> &Self;
fn cast_mut(t: &mut T) -> &mut Self;
}
impl<T> Cast<T> for Foo
where
T: Foo + 'static,
{
fn cast(t: &T) -> &(Foo + 'static) {
t
}
fn cast_mut(t: &mut T) -> &mut (Foo + 'static) {
t
}
}
impl Foo for i32 {
fn method(&self) {
println!("{}", self);
}
}
fn generic<A: Cast<B> + ?Sized, B>(b: &B, f: fn(&A)) {
let obj: &A = A::cast(b);
f(obj);
}
fn main() {
generic::<Foo, i32>(&99, Foo::method);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment