Modules are used to organize the code that can be maintained and reused more easily. We can encapsulate the related code into a module and enhance the visibility of the code.
Let’s create a module in Julia.
module
keywordWe use the module
keyword followed by the name of the module.
module MyModule
export
keywordAfter declaring the module, we use the export
keyword followed by the function names that should be visible where we import this module.
module MyModule
export sum_function
sum_function()
functionThis function accepts two variables, a
and b
, and returns their sum.
function sum_function(a, b)
return a + b
end
There are two ways to use a created module in another piece of code.
using
keywordWe use the using
keyword to import the entire module and all its exported variables and functions.
using MyModule
Let’s run the following code to understand the working of the using
module:
module MyModuleexport sum_functionfunction sum_function(a, b)return a + bendend # end of module definition
include()
function to include the mymodule.jl
file in the current namespace.using
keyword to completely import the MyModule
module.sum_function()
function with arguments 2
and 3
and store the result in a variable result
.result
variable to the console.import
keywordWe use the import
keyword to import the specific module and make the specified functions or variables available. It is useful when we require a small subset of the functionality provided by a module.
import MyModule.sum_function
Let’s run the following code to understand the working of the import
module:
include("mymodule.jl")import MyModule.sum_functionresult = sum_function(2, 3)print(result)
include()
function to include the file mymodule.jl
in the current namespace.import
keyword to selectively import the sum_function()
function from the MyModule
module.sum_function()
function with arguments 2
and 3
and store the result in a variable result
.result
variable to the console.Free Resources