Multiple namespaces

I was aware that methods and fields reside in separate namespaces, and can therefore have overloaded names. Nonetheless I was surprised to discover that syn::Ident has different meanings here

let _wow: syn::Ident = input.parse()?;
let _wow = syn::Ident::parse(input)?;
let _wow = input.peek(syn::Ident);

being a type in the first two occurrences and a function in the third. In fact, the definition of the function is

pub fn Ident(marker: lookahead::TokenMarker) -> Ident {
    match marker {}
}

which is fun: fn LookAtMe(...) -> LookAtMe {...}.

[rust-analyzer seems to gloss over this difference at times, which delayed the discovery ... as did the non-standard style in naming the function.]

I'm left wondering what the consequences of this are for things like use syn::Ident. If both are public, can I choose to bring only one into scope?

In general, where can I read more about the various namespaces in Rust? There are clearly more of them than I had assumed until now. How many more different meanings of syn::Ident would it be possible to have?

https://doc.rust-lang.org/stable/reference/names/namespaces.html

There're 5, but 2 of them - lifetime and label namespace - are easily distinguishable due to single quote prefix and can't be used so you may only care other 3 namespaces.

No. use brings every items belong to the name to current namespace. From the compiler's perspective there's nothing to be confused as every syntaxes which take names only care single kind of namespace. But humans are not compiler, it's highly recommended that every items belong to same name should refer to logically same thing. It's one of the reasons why the rustc have built in naming convention lints.

3 Likes

Note that Rust haven't invented that particular feature. C++ have it and it inherited it from C. struct stat nad function stat thingie existed for decades.

Only Rust's treatment of these is similar to C and not to C++. That's why Rust includes turbo fish and doesn't include typename keyword.

Separate namespaces for functions and values (and more) have been around in Lisps since before [1] C was a twinkle in Ritchie's eye.


  1. probably - can't quickly find a reference to exactly when they first appeared there, but they were definitely present in a bunch of dialects that predate Common Lisp ↩︎

Common Lisp is much younger than C thus we would need to go further to find out whether this is invention of Lisp or not… but I just don't understand how that would be relevant: Rust is “an ML dialect in C++ trenchcoat” which means that while semantic of many things is borrowed from ML (and thus, indirectly, from Lisp) it's syntax is mostly based on C++ (and other curly-bracket langauges).

Last time I've checked there was no Curly-braced Lisp dialects so why do you bring Lisp here?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.