How to import a custom module in Julia
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.
Create a module
Let’s create a module in Julia.
The module keyword
We use the module keyword followed by the name of the module.
module MyModule
The export keyword
After 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
The sum_function() function
This function accepts two variables, a and b, and returns their sum.
function sum_function(a, b)
return a + b
end
Use a module
There are two ways to use a created module in another piece of code.
The using keyword
We 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
Explanation
- Line 1: We use the
include()function to include themymodule.jlfile in the current namespace. - Line 2: We use the
usingkeyword to completely import theMyModulemodule. - Line 4: We call the
sum_function()function with arguments2and3and store the result in a variableresult. - Line 6: We prints the value of the
resultvariable to the console.
The import keyword
We 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)
Explanation
- Line 1: We use the
include()function to include the filemymodule.jlin the current namespace. - Line 2: We use the
importkeyword to selectively import thesum_function()function from theMyModulemodule. - Line 4: We call the
sum_function()function with arguments2and3and store the result in a variableresult. - Line 6: We print the value of the
resultvariable to the console.
Free Resources