How to match on data type in Rust?

前端 未结 1 430
再見小時候
再見小時候 2020-12-03 14:27

I\'m trying to match on the datatype of a generic field of a struct and react accordingly. My general idea was like this (code doesn\'t compile):

struct Foo&         


        
相关标签:
1条回答
  • 2020-12-03 15:15

    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:

    • Why is this match pattern unreachable when using non-literal patterns?

    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 :)

    0 讨论(0)
提交回复
热议问题