Basics

Nim Modules

Using Nim Modules

Nim modules use import and export for code organization.

Introduction to Nim Modules

Nim is a statically typed compiled systems programming language that focuses on efficiency, expressiveness, and elegance. One of the key features of Nim is its module system, which allows developers to organize code into separate, reusable components. Modules in Nim use import and export to manage dependencies and access control.

Creating a Nim Module

Creating a module in Nim is straightforward. You simply save your code in a .nim file, and the file name becomes the module name. Let's create a basic module named mathutils that contains a function to add two numbers.

Importing Modules

To use the functions defined in a module, you need to import it into your Nim program. You can import a module using the import statement. Here's how you can import and use the mathutils module in another program:

Selective Imports

Nim also allows selective imports, which enable you to import only specific symbols from a module. This can be useful for reducing namespace pollution. Here’s how you can selectively import the add function from the mathutils module:

Exporting Symbols

By default, all top-level symbols in a module are exported. However, you can control what is exported using the {.export.} pragma. This pragma allows you to specify which procedures, types, or variables should be accessible to other modules.

Conclusion

Nim's module system facilitates clean and organized code by making it easy to import and export functionality across different parts of a program. Understanding how to effectively use modules is a fundamental skill for any Nim developer, ensuring that your code remains modular, reusable, and easy to maintain.