How to match on data type in Rust?

Idiomatic Solution

Create a trait which constrains the parameter T in Foo, implement any specific behavior as an associated function of this trait.

Example:

trait PrintMe {
    fn print_me(&self);
}

impl PrintMe for String {
    fn print_me(&self) { println!("I am a string"); }
}

struct Foo<T: PrintMe> {
    bar: T
}

fn main() {
    // ...
    x.bar.print_me();
}

This is principled generic programming, where you declare exactly the difference of behavior of the possible generic parameters, so that there is no surprise.

See also:


Exact Solution

Rust can indeed query types: each type has a unique TypeId associated, and you can match on TypeId with a series of if checks. It’s clunky.

fn print_me<T>(x: &Foo<T>) {
    if TypeId::of::<T>() == TypeId::of::<String>() {
        println!("I am a string");
    } else // ...
}

But please… don’t do that 🙂

Leave a Comment