Rust Tutorial: Crates and Modules in Rust
Organize code into modules and use the standard library.
Concepts in this chapter
You will learn and practice:
- **mod** — declare a module; code in same file or mod.rs / file.rs
- **use** — bring items into scope: use std::collections::HashMap;
- **pub** — make items public for other modules
- **std** — standard library; Vec, HashMap, Option, Result, etc.
- **Cargo** — crate = package; dependencies in Cargo.toml
---
use and std
```rust
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("a", 1);
}
```
---
Nested modules
```rust
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
}
fn main() {
println!("{}", math::add(2, 3));
}
```
---
What's Next?
Next: **Threads and Channels** — concurrency in Rust.
What you'll learn in this Rust crates and modules in rust tutorial
This interactive Rust tutorial has 2 hands-on exercises. Estimated time: 10 minutes.
- use and Vec — Use std::collections (or just Vec from prelude is already there). Create a Vec with vec!["one", "two"], then print its l…
- HashMap from std — Add use std::collections::HashMap. Create a HashMap, insert "a" -> 1 and "b" -> 2, then print the value for "a".
Rust Crates and Modules in Rust concepts covered
- Concepts in this chapter
- use and std
- Nested modules
- What's Next?