Single statement using all 5 of Rust's namespaces: break 'A A::<'A, A>(A!())

261 points Tyilo 37 comments

It was fun figuring out how to write a single Rust statement that uses each of the 5 namespaces once:

#![allow(non_snake_case)]
#![allow(clippy::extra_unused_lifetimes)]

use std::marker::PhantomData;

struct A<'A, A = ()>(PhantomData<&'A A>);

macro_rules! A {
    () => {
        PhantomData
    };
}

pub fn f<'A>() {
    'A: {
        // All 5 A's are in different namespaces.
        // See https://doc.rust-lang.org/reference/names/namespaces.html
        // In order:
        // - `A - label namespace
        // - A  - value namespace
        // - 'A - lifetime namespace
        // - A  - type namespace
        // - A! - macro namespace
        break 'A A::<'A, A>(A!());
    };
}

Playground

List of Rust namespaces: https://doc.rust-lang.org/reference/names/namespaces.html

Edit: Fixed swapped value and type namespace in comment. Thanks u/kmdreko.