-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
The only requirement here is that your generic trait implements
Cast
as shown in line 11.