Manually checking for specific custom type

Hello,

For example if I have this custom struct:

struct Plus<T:Exp> {
  v : Vec<T>
}

and in another function I want to check if a variable given as a parameter to that function is of that Plus<T:Exp> type:

fn parse(&self, left: Exp)->Opt<Exp>{
    if(left == PlusN) {
    ...
    }
    ...
}

is there a way to check if a variable is of specific type?

Rust is fundamentally different from dynamic languages with runtime type information. Checking for a type is not possible in most cases, and limited and cumbersome in special cases (see dyn Any).

Above all, it's considered a wrong approach in Rust.

Instead of checking for a specific type, you should use trait bounds to require specific operations you want, and use those operations without checking. If you need type-specific implementations, move them to the trait implementation for each type, instead of ifs in the code using the type.

If you need to support one of several specific types (like AST nodes), use enum and match.

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.