namespace Foo { 
    int x = 0; 
    int f() { return x; }  

As in C++, namespaces are used to avoid name clashes in code. For example: declares an integer named Foo::x and a function named Foo::f. Note that within the namespace, you don’t need to use the qualified name. For instance, Foo::f refers to Foo::x as simply x. We could also simply write “namespace Foo;” (note the trailing semi-colon) and leave out the enclosing braces. Every declaration (variables, functions, types, typedefs) following this namespace declaration would be placed in the Foo namespace.

As noted before, you can refer to elements of a namespace using the “::” notation. Alternatively, you can open up a namespace with a “using” declaration. For example, we could follow the above code with:

  namespace Bar {  
    using Foo { 
      int g() { return f(); } 
    int h() { return Foo::f(); } 

Here, we opened the Foo namespace within the definition of Bar::g. One can also write “using Foo;” to open a namespace for the remaining definitions in the current block.

Namespaces can nest as in C++.

Currently, namespaces are only supported at the top-level and you can’t declare a qualified variable directly. Rather, you have to write a namespace declaration to encapsulate it. For example, you cannot write “int Foo::x = 3;.”

The following subtle issues and implementation bugs may leave you scratching your head: