Nim provides default language features by default.

If you want extra functionality or features, you can extend them by reusing modules.

Nim Modules import example

Modules are reusable functionalities that can be reused across all applications.

Let’s see how we can use Inbuilt Nim Modules.

strutils is a string module that contains procedures such as split, length, etc.

First You have to import the module into a code using the import keyword

import std/strutils
or
import strutils

Here is an example that uses the split procedure, which converts the string into multiple strings delimited by space. Result is sequenced

Here is an example

import std/strutils

let str = "one two three"
var result=str.split(' ')
echo result
echo typeOf(result)

Output:

@["one", "two", "three"]
seq[string]

How to create a Custom module and import in Nim code

Sometimes, We want to create a custom code that needs to be reused across multiple modules

Let’s create a simple module ie calculator.nim

  • It contains two procedures
  • add, contains
    • asterisk (*) that tells that importing this file can use procedure name.
  • substract that does not contains asterik(*), this method is not visible during import.
proc add*(values: varargs[int]): int  =
    for value in items(values):
      total += value
proc subtract(value1: int, value2: int): int  =
    return value1 -  value2

Now, Test the calculator.nim module First, import a custom module using the import

  • add method can be used
  • subtract throws an error as it is invisible

Test.nim:

import calculator
echo add(1,4,7,9)      # 21
echo subtract(20, 4) # error

Suppose, you have multiple files in a directory and subdirectory as given below

.
├── calculator
│   ├── add.nim
│   └── subtract.nim
│   └── division.nim
├── shapes
│   └── circle.nim
├── one.nim
└── two.nim
└── three.nim

You can import the files as given below.

import one
import two
import three
import shapes/circle
import calculator / [add, subtract, division]