Macro matcher branching on particular path

⚓ Rust    📅 2025-08-06    👤 surdeus    👁️ 5      

surdeus

I am learning macros and I came up with the following broken code:

mod x {
    pub const V: usize = 1;

    pub mod a {
        pub const V: usize = 2;
    }

    pub mod b {
        pub const V: usize = 3;
    }

    pub mod c {
        pub mod cc {
            pub const V: usize = 4;
        }
    }

    macro_rules! show_token {
        ($($t:path),*) => {
            $(
                show_token!(@print_single $t);
            )*
        };

        (@print_single self) => {
            println!("'{}'+++", self::V * 333);
        };

        (@print_single $t:path) => {
            println!("'{}'", $t::V);
        };
    }

    pub fn run() {
        show_token!(self, a, b, c::cc);
    }
}

fn main() {
    x::run();
}

The aim is simple, to have distinct behavior if self is provided as path.

Playground module with path - compilation error

Playground module with token tree - executes as I would expect

Playground submodule with token tree - compilation error

Playground submodule with path - compilation error

3 posts - 2 participants

Read full topic

🏷️ Rust_feed