How to "see through" a type alias

I have a type SampleType declared like this:

type SampleType = i8;

I also have a match statement that looks like this:

match stringify!(SampleType) {
        "i8" | "i16" | "i32" => {...},
        "f32" => {...},
        _ => panic!("Error: Unsported Type {}", stringify!(SampleType)),
}

How do I make SampleType decompose into the type that is behind it (i.e. assert!(stringify!(SampleType) == "i8")? It would be much preferable to use a type alias as this type is used in different places arond the program, and is frequently changed. I cant seem to find out how to do this. Is this even possible?

It's not because macros don't know anything about types. They just receive the literal token SampleType and the compiler doesn't even know at that point what it actually is. What is the actual problem you're trying to solve here?

1 Like

To make a match statement that will return an enum variant or panic if the type is not supported. This is the exact code:

 match stringify!(SampleType) {
        "i8" | "i16" | "i32" => hound::SampleFormat::Int,
        "f32" => hound::SampleFormat::Float,
        _ => panic!("Error: Unsupported Type {}", stringify!(SampleType)),
}

When you want to compute something about a type, you use a trait, because traits can act as functions within the type system. Runnable example:

#[derive(Debug)]
enum SampleFormat {
    Int,
    Float,
}

trait TypeToFormat {
    const FORMAT: SampleFormat;
}
impl TypeToFormat for i8 {
    const FORMAT: SampleFormat = SampleFormat::Int;
}
impl TypeToFormat for i16 {
    const FORMAT: SampleFormat = SampleFormat::Int;
}
impl TypeToFormat for i32 {
    const FORMAT: SampleFormat = SampleFormat::Int;
}
impl TypeToFormat for f32 {
    const FORMAT: SampleFormat = SampleFormat::Float;
}

type SampleType = i8;

fn main() {
    dbg!(SampleType::FORMAT);
}
5 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.