🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Module Namespaces

A namespace is a named container that keeps its own names separate from names outside it. A module in Julia is a namespace.

Qualified access reaches a name through its module

Greeter holds a hello function. Its full path reaches it.

module Greeter
function hello()
return "Hello from Greeter"
end
end
println(Greeter.hello())

Two modules can hold the same name

First and Second each hold a value function. Adding their results shows both exist.

module First
function value()
return 10
end
end
module Second
function value()
return 20
end
end
println(First.value() + Second.value())

A short name stays inside its own module

MathTools holds a double function. The qualified call doubles 21.

module MathTools
function double(x)
return x * 2
end
end
println(MathTools.double(21))

Example

module Area
function square(x)
return x * x
end
end
module Border
function square(x)
return 4 * x
end
end
println(Area.square(3))
println(Border.square(3))

Key points

  • Namespace: a module keeps its names apart from names in other modules.
  • Qualified access: write the module name, a dot, and the function name to reach a name inside a module.
  • Same name: two modules can each hold a function with the same name.
  • Different results: the same short name can give a different result in each module.
  • No extra step: qualified access reaches a name directly through its module.

In this example, Area and Border each define a square function. The first call uses the Area version and prints 9. The second call uses the Border version and prints 12. The same short name gives a different result in each module.

Note

Julia module names start with a capital letter by convention.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does Greeter.hello() do?