Marc HPunkt
Marc HPunkt

Reputation: 439

Macro to use import depending on type alias

I have a type alias pub type Float = std::f64 which I can change to f32 if I want to.

The problem is I need to use PI from either the std::f32 or f64 lib. The way of solving this would be to use a macro which can expand into the correct use declaration.

The first problem I have is that I don't know how to expand Float.

macro_rules! more {
($x:tt) => (stringify!(x));
}

gives me "Float" not "std::f64". is it possible to solve this(and my general problem) in this manner?

Edit:

Essentially my final goal is something like this:

macro_rules! final {

($x:tt) => (use_correct_import!(x)); // use std::f32 or use::std::f64 depending on Float

}

Upvotes: 0

Views: 316

Answers (1)

nnnmmm
nnnmmm

Reputation: 8744

You need to define two aliases: One for the type itself, one for the module which contains the constants. You could of course just use those two declarations directly:

use std::f64 as float;
type Float = f64;

fn main() {
    let pi: Float = float::consts::PI;
    println!("{}", pi);
}

But if you want to have a single place where you can switch between the two, you can use a macro like this:

macro_rules! define_float {
    ($f:tt) => {
        use std::$f as float;
        type Float = $f;
    }
}

define_float!(f64);

fn main() {
    let pi: Float = float::consts::PI;
    println!("{}", pi);
}

Upvotes: 1

Related Questions