TypeId equality check

Hi,
I was wondering why

pub fn return_concrete_type_result<T: some_constraints>(&self, for_type: T) {
    if dat.type_id() == TypeId::of::<MyType>() {
       println!("Equals");
}

and

pub fn return_concrete_type_result<T: some_constraint>(&self, for_type: T) {
   let b = TypeId::of::<MyType>();
   match for_type.type_id() {
       b => { println!("Equals") }
       _ => panic!("Unimplemented Type")
}

works
but

pub fn return_concrete_type_result<T: some_constraint>(&self, for_type: T) {
    match for_type.type_id() {
      TypeId::of::<MyType>() => { println!("Equals") }
      _ => panic!("Unimplemented")
    }
}

Dont work! Infact does compile.
The compiler complains:

TypeId
Go to TypeId

expected tuple struct or tuple variant, found associated function `TypeId::of::<Unit>`
for more information, visit https://doc.rust-lang.org/book/ch18-00-patterns.htmlrustcClick for full compiler diagnostic

From what I can see both .type_id() and TypeId::of::<>() are returning TypeId structures, unless I cannot just compare structures like that, but then the message doesnt feel accurate, like some of the other messages with help included.

I'm sure is something basic, but I cant seem to understand :woozy_face:

Any ideas
Thanks,

Well, try this:

pub fn return_concrete_type_result<T: some_constraint>(&self, for_type: T) {
   let b = TypeId::of::<i32>(); // not MyType
   match for_type.type_id() {
       b => { println!("Equals") }
       _ => panic!("Unimplemented Type")
}

It still works. Interesting, huh? Because the left hand side of the match arm("=>") takes pattern not expression.

You can learn more about patterns here.

https://doc.rust-lang.org/stable/book/ch06-02-match.html
https://doc.rust-lang.org/stable/book/ch18-00-patterns.html

3 Likes

The warnings rustc gives you are relevant (here specifically but also more generally).

1 Like