docs: add module hierarchy section (#22919)

This commit is contained in:
Bruno-Vdr 2024-11-20 08:00:23 +01:00 committed by GitHub
parent ad24dbdff1
commit 26837d4862
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -87,6 +87,7 @@ by using any of the following commands in a terminal:
* [Module imports](#module-imports) * [Module imports](#module-imports)
* [Selective imports](#selective-imports) * [Selective imports](#selective-imports)
* [Module hierarchy](#module-hierarchy)
* [Module import aliasing](#module-import-aliasing) * [Module import aliasing](#module-import-aliasing)
* [Statements & expressions](#statements--expressions) * [Statements & expressions](#statements--expressions)
* [If](#if) * [If](#if)
@ -1577,6 +1578,54 @@ println('Name: ${name}')
current_os := user_os() current_os := user_os()
println('Your OS is ${current_os}.') println('Your OS is ${current_os}.')
``` ```
### Module hierarchy
> [!NOTE]
> This section is valid when .v files are not in the project's root directory.
Modules names in .v files, must match the name of their directory.
A .v file `./abc/source.v` must start with `module abc`. All .v files in this directory
belong to the same module `abc`. They should also start with `module abc`.
If you have `abc/def/`, and .v files in both folders, you can `import abc`, but you will have
to `import abc.def` too, to get to the symbols in the subfolder. It is independent.
In `module name` statement, name never repeats directory's hierarchy, but only its directory.
So in `abc/def/source.v` the first line will be `module def`, and not `module abc.def`.
`import module_name` statements must respect file hierarchy, you cannot `import def`, only
`abc.def`
Refering to a module symbol such as a function or const, only needs module name as prefix:
```v ignore
module def
// func is a dummy example function.
pub fn func() {
println('func')
}
```
can be called like this:
```v ignore
module main
import def
fn main() {
def.func()
}
```
A function, located in `abc/def/source.v`, is called with `def.func()`, not `abc.def.func()`
This always implies a *single prefix*, whatever sub-module depth. This behavior flattens
modules/sub-modules hierarchy. Should you have two modules with the same name in different
directories, then you should use Module import aliasing (see below).
### Module import aliasing ### Module import aliasing