Rust modules: Difference between revisions
From wikinotes
No edit summary |
No edit summary |
||
Line 2: | Line 2: | ||
The <code>std::prelude</code> module is included in the scope of every program. | The <code>std::prelude</code> module is included in the scope of every program. | ||
= Naming/Paths = | |||
<blockquote> | |||
Module names govern where they can be found within the filesystem.<br> | |||
Module locations are based on where they are defined | |||
<pre> | |||
# from the rust book: | |||
backyard | |||
├── Cargo.lock | |||
├── Cargo.toml | |||
└── src | |||
├── garden | |||
│ └── vegetables.rs | |||
├── garden.rs | |||
└── main.rs | |||
</pre> | |||
The module <code>foo</code>'s code could be | |||
* <code>src/foo.rs</code> | |||
* <code>src/foo/mod.rs</code> | |||
</blockquote><!-- Naming/Paths --> | |||
= Imports = | |||
<blockquote> | |||
<syntaxhighlight lang="rust"> | <syntaxhighlight lang="rust"> | ||
use std::io; | use std::io; // merges objects from namespace into your own | ||
use std::fs::File; // merge 'File' only into current namespace | |||
std::io::stdin() // you also can access objects from their namespace | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Imports --> | |||
= Access Control = | |||
<blockquote> | |||
By default, a module's code is public to itself and it's children,<br> | |||
but private to it's parents and/or callers. | |||
<syntaxhighlight lang="rust"> | |||
pub mod house { | |||
pub mod livingroom { | |||
// ... | |||
} | |||
mod bedroom { | |||
// ... | |||
} | |||
} | |||
</syntaxhighlight> | |||
</blockquote><!-- Access Control --> |
Revision as of 23:03, 7 February 2023
Modules are rust libraries.
The std::prelude
module is included in the scope of every program.
Naming/Paths
Module names govern where they can be found within the filesystem.
Module locations are based on where they are defined# from the rust book: backyard ├── Cargo.lock ├── Cargo.toml └── src ├── garden │ └── vegetables.rs ├── garden.rs └── main.rsThe module
foo
's code could be
src/foo.rs
src/foo/mod.rs
Imports
use std::io; // merges objects from namespace into your own use std::fs::File; // merge 'File' only into current namespace std::io::stdin() // you also can access objects from their namespace
Access Control
By default, a module's code is public to itself and it's children,
but private to it's parents and/or callers.pub mod house { pub mod livingroom { // ... } mod bedroom { // ... } }