Modules
Nim supports splitting a program into pieces by a module concept. Each module needs to be in its own file and has its own namespace. Modules enable information hiding and separate compilation. A module may gain access to the symbols of another module by the import statement. Recursive module dependencies are allowed, but are slightly subtle. Only top-level symbols that are marked with an asterisk (*) are exported. A valid module name can only be a valid Nim identifier (and thus its filename is identifier.nim).
The algorithm for compiling modules is:
- Compile the whole module as usual, following import statements recursively.
- If there is a cycle, only import the already parsed symbols (that are exported); if an unknown identifier occurs then abort.
This is best illustrated by an example:
# Module A
type
T1* = int # Module A exports the type `T1`
import B # the compiler starts parsing B
proc main() =
var i = p(3) # works because B has been parsed completely here
main()
# Module B
import A # A is not parsed here! Only the already known symbols
# of A are imported.
proc p*(x: A.T1): A.T1 =
# this works because the compiler has already
# added T1 to A's interface symbol table
result = x + 1
当前内容版权归 nim-lang.org 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 nim-lang.org .