Skip to content

Instantly share code, notes, and snippets.

@victor-iyi
Last active November 15, 2021 07:57
Show Gist options
  • Save victor-iyi/a55322b4d78b8f60b3138fc4c275e011 to your computer and use it in GitHub Desktop.
Save victor-iyi/a55322b4d78b8f60b3138fc4c275e011 to your computer and use it in GitHub Desktop.
Implement InstanceOf trait in Rust
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