Jang Myoungwoo
Jang Myoungwoo

Reputation: 35

What's the meaning of starting with :: Rust macro

I saw macro coding right below.

Why should :: be first of the statement and what does it mean?

::std::collections::HashMap::new()

macro_rules! hashmap {
    () => {
        {
            ::std::collections::HashMap::new()
        }
    };
    ($($k:expr => $v:expr),*) => {
        {
            let mut _map = ::std::collections::HashMap::new();
            $(_map.insert($k, $v);)*
            _map
        }
    };
    ($($k:expr => $v:expr),+ $(,)?) => {
        {
            let mut _map = ::std::collections::HashMap::new();
            $(_map.insert($k, $v);)*
            _map
        }
    };
}

Upvotes: 1

Views: 101

Answers (2)

Sudip Ghimire
Sudip Ghimire

Reputation: 715

Path starting with :: means that search in global namespace. Since @Chayin already pointed the documentation, A example might be useful for you and future readers. When you run this program: test-program/src/main

mod std {
    pub mod f64 {
        pub mod consts {
            pub const PI: f64 = 4.0;
        }
    }
}

macro_rules! test_mactro {
    () => {{
        pub mod std { pub mod f64 { pub mod consts {
            pub const PI: f64 = 5.0;
        }}}

        println!("{}", std::f64::consts::PI);
        println!("{}", ::std::f64::consts::PI);
        println!("{}", self::std::f64::consts::PI);
    }};
}

fn main() {
    test_mactro!()
}

And see the output:

$ cargo run
5
3.141592653589793
4

Upvotes: 2

Chayim Friedman
Chayim Friedman

Reputation: 71025

It means "search in the global namespace". See the documentation.

It basically means (in edition 2018 and beyond) to not search in this crate. Suppose we were using unqualified std::collections::HashMap (without the leading ::), and the macro was used in a module that defines a std submodule, like that:

mod std;

hashmap! {}

In this case, the declared std module will take precedence over the preexisting std library, and the macro will refer to it. Of course there isn't a collections::HashMap in there (or worse, there is but it is different from the expected HashMap). To prevent that, we use ::std and that means "search for a crate named std, do not look for modules with that name".

Upvotes: 4

Related Questions