Can I do compile time "if"?

I'm searching for the equivilant of D's static if or C++'s if constexpr or #if with macros. Is there a way to do something like that in Rust? I want to include code based on the type of the variable given in a macro

You can't do this directly because macros don't have access to information about the types of variables—type inference happens later in compilation. Instead, you'll have to defer the "if" by using a trait that has different implementations for different types.

1 Like

What is this supposed to mean? You cannot see my post?

What "defer" the if means? Can you make an example with and &str and let's say an i32?

Not with macros, but if has been supported in Rust const expressions since last year. The code still has to typecheck, though, so you won’t be able to compare unlike types, only values of a single type.

1 Like

I deleted my own post because I realized my answer didn't apply to your case.

Oh, ok

I understand! Thanks a lot for the help!

One more thing you can do is check for the TypeId of a type, since TypeId::of() is a const fn. This will let you branch on a type, but it will still not allow you to actually use a value of that type dynamically.

1 Like

Here's a simple example of what I'm thinking of:

macro_rules! do_it {
    ($x:expr) => {
        $crate::_DoIt::do_it($x)
    };
}

// implementation detail, use the macro instead of referring to this trait directly
pub trait _DoIt {
    fn do_it(self);
}

impl _DoIt for i32 {
    fn do_it(self) {
        // code for i32 goes here...
    }
}

impl<'a> _DoIt for &'a str {
    fn do_it(self) {
        // code for &str goes here...
    }
}

Now do_it!(17) will result in calling the code for i32, and do_it!("foo") will result in calling the code for &str. The choice between the two is deferred to the trait system.

1 Like

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.