Nim Modules
Modules are a powerful way to organize and manage code in Nim. They can help you to make your programs more modular and easier to maintain.
To create a module, you create a file with the .nim extension. The file can contain any number of functions and variables. When you use a function or variable from a module, you need to import the module into your program.
To import a module, you use the import keyword followed by the name of the module. For example, if you have a module called "math" that contains a function called "add", you would import it into your program like this:
import math
Once you have imported a module, you can use its functions and variables in your program.
Example
Here's an example of how to call a function and procedure defined in a module using Nim:
Suppose we have a module called "utilities.nim" that defines a "multiply" function and a "printMessage" procedure. Here's what the contents of "utilities.nim" might look like:
# utilities.nim module
proc printMessage(message: string) =
echo message
proc multiply(x: int, y: int): int =
return x * y
To call these functions/procedures in another file, we can import the "utilities" module and then call the functions/procedures using the dot notation. Here's an example of how to do that in another file called "main.nim":
# main.nim file
import utilities
var x = 5
var y = 10
let result = utilities.multiply(x, y)
echo result # Output: 50
utilities.printMessage("Hello, world!") # Output: Hello, world!
In this example, we import the "utilities" module using the "import" statement, and then call the "multiply" function and "printMessage" procedure using the dot notation. We pass arguments to the functions/procedures as needed.
Read next: Errors