Hacky ways to import from a specific namespace

This is just out of curiosity, but I found a way to import from a specific namespace (module ≠ namespace = one of TypeNS, ValueNS or MacroNS).

mod m0 {
    pub(crate) struct Color; // TypeNS + ValueNS
}

mod m1 {
    mod tmp {
        pub(crate) use crate::m0::Color;
    }
    pub(crate) use tmp::*;

    #[allow(dead_code)]
    type Color = i32;
}

pub(crate) use crate::m1::Color; // ValueNS only

pub fn foo() {
    let _x = Color;
    // let _x: Color = Color; // error
}

For importing from TypeNS, there's a simpler way (although it doesn't seem like an expected behavior of ::{self}):

mod m0 {
    pub(crate) struct Color; // TypeNS + ValueNS
}

pub(crate) use crate::m0::Color::{self}; // TypeNS

pub fn foo() {
    let _x: Color;
    // let _x: Color = Color; // error
}
1 Like

The first one can be simplified to

mod m0 {
    mod tmp {
        pub(crate) struct Color; // TypeNS + ValueNS
    }
    pub(crate) use tmp::*;

    #[allow(dead_code)]
    type Color = ();
}

pub(crate) use crate::m0::Color; // ValueNS only

pub fn foo() {
    let _x = Color;
    // let _x: Color = Color; // error
}

The second one can be circumvented by adding the #[allow(legacy_constructor_visibility)] annotation.


This is really interesting, and strange how glob imports interact with namespaces.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.