Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Last active May 3, 2024 03:52
Show Gist options
  • Save matthewjberger/6660bfd2f5c8434471722c1ece94174b to your computer and use it in GitHub Desktop.
Save matthewjberger/6660bfd2f5c8434471722c1ece94174b to your computer and use it in GitHub Desktop.
Type id pattern matching in rust
use std::any::TypeId;
// Define some example types
struct Foo;
struct Bar;
struct Baz;
// Define a function to perform type-based pattern matching and return the value
fn match_type<T: 'static>(value: T) -> Option<T> {
// Get the TypeId of the value
let type_id = TypeId::of::<T>();
// Match the TypeId with the known types
match type_id {
id if id == TypeId::of::<Foo>() => {
println!("The value is of type Foo");
Some(value)
}
id if id == TypeId::of::<Bar>() => {
println!("The value is of type Bar");
Some(value)
}
id if id == TypeId::of::<Baz>() => {
println!("The value is of type Baz");
Some(value)
}
_ => {
println!("The type is not recognized");
None
}
}
}
fn main() {
let foo = Foo;
let bar = Bar;
let baz = Baz;
if let Some(foo) = match_type(foo) {
// Do something with foo of type Foo
println!("Received value of type Foo");
}
if let Some(bar) = match_type(bar) {
// Do something with bar of type Bar
println!("Received value of type Bar");
}
if let Some(baz) = match_type(baz) {
// Do something with baz of type Baz
println!("Received value of type Baz");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment