Rust modules: Difference between revisions
From wikinotes
Line 42: | Line 42: | ||
= Imports = | = Imports = | ||
<blockquote> | <blockquote> | ||
* <code>use</code> merge namespace into current (ex. <code>use foo; myfn();</code>) | |||
* <code>mod</code> enables you to access from namespace (ex. <code>mod foo; foo::myfn();</code>) | |||
<code>use</code> (merge with current namespace) | |||
<syntaxhighlight lang="rust"> | <syntaxhighlight lang="rust"> | ||
use std::io; // merges objects from namespace into your own | use std::io; // merges objects from namespace into your own | ||
Line 49: | Line 53: | ||
std::io::stdin() // you also can access objects directly from their namespace without `use` | std::io::stdin() // you also can access objects directly from their namespace without `use` | ||
</syntaxhighlight> | |||
<code>mod</code> (access namespace) | |||
<syntaxhighlight lang="rust"> | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Imports --> | </blockquote><!-- Imports --> |
Revision as of 03:04, 8 February 2023
Modules are rust libraries.
The std::prelude
module is included in the scope of every program.
Documentation
cargo book: package layout https://doc.rust-lang.org/cargo/guide/project-layout.html
Entrypoint
For modules to be compiled, they must be used (however indirectly)
from either your crate'smain.rs
orlib.rs
.
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
merge namespace into current (ex.use foo; myfn();
)mod
enables you to access from namespace (ex.mod foo; foo::myfn();
)
use
(merge with current namespace)use std::io; // merges objects from namespace into your own use std::io::*; // use std::fs::File; // import 'File' only into current namespace use std::fs::{File, DirBuilder}; // import multiple types/functions into current namespace std::io::stdin() // you also can access objects directly from their namespace without `use`
mod
(access 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 { // ... } }