Skip to content

Instantly share code, notes, and snippets.

@torkleyy
Forked from rust-play/playground.rs
Last active March 26, 2018 06:16
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 torkleyy/84859fd57f89acca5524e0d4dfd2d0fc to your computer and use it in GitHub Desktop.
Save torkleyy/84859fd57f89acca5524e0d4dfd2d0fc to your computer and use it in GitHub Desktop.
How to cast a generic `T: O` to a generic trait object `O` in Rust
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);
}
@torkleyy
Copy link
Author

The only requirement here is that your generic trait implements Cast as shown in line 11.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment