Last active
November 15, 2021 07:57
-
-
Save victor-iyi/a55322b4d78b8f60b3138fc4c275e011 to your computer and use it in GitHub Desktop.
Implement InstanceOf trait in Rust
This file contains 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
use std::any::{Any, TypeId}; | |
trait InstanceOf | |
where | |
Self: Any | |
{ | |
fn instance_of<U: ?Sized + Any>(&self) -> bool { | |
TypeId::of::<Self>() == TypeId::of::<U>() | |
} | |
} | |
// Impment this trait for any type that implements `Any` (which is most types). | |
// impl<T: ?Sized + Any> InstanceOf for T {} | |
impl InstanceOf for String {} | |
fn main() { | |
let actually_a_string = some_unknown_function(); | |
let mut a_string = String::new(); | |
if actually_a_string.instance_of::<String>() { | |
a_string = actually_a_string; | |
} | |
println!("{}", a_string); | |
} | |
fn some_unknown_function() -> String { | |
"I'm actually a string!".into() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment