Crate match_type

source ·
Expand description

This crate provides a single macro, match_type, which allows you to “match” on the type of an expression at compile time.

As it stands, it is not possible in Rust to reflect on the type of an expression when defining a macro. However, there are situtations where we would like a macro to expand differently depending on what the type of an expression we are given is.

Say for example we would like to write a macro as_string that turns the given expression into some string representation in some way. The type of the expression might implement Display, or it might implement Debug, or both, or neither. With match_type we can implement such a macro easily:

use match_type::match_type;
use std::fmt::{Debug, Display};

macro_rules! as_string {
    ($e:expr) => {
        match_type!(
            $e {
                <T: Display> T => String: format!("{}", self),
                <T: Debug>   T => String: format!("{:?}", self),
                _              => &'static str: stringify!($e),
            }
        )
    };
}

For more information, see the documentation of match_type, and take a look at the README.md on Github.

Macros

  • Allows you to match on the type of an expression.