Week 6: Modules & Crates (Beginner)
Overview
Week 6 focuses on organizing code in Rust using modules, packages, and crates. You’ll learn how to structure larger projects, create reusable libraries, and document your code. This is the last week covering beginner concepts before moving to intermediate Rust topics.
Day 1-3: Modules and Visibility
Topics
- The module system:
- Creating modules with
mod
- Module hierarchies
- Inline modules vs separate files
- Creating modules with
- Visibility rules:
- Public (
pub
) items - Private items (default)
- Restricted visibility (
pub(crate)
,pub(super)
, etc.)
- Public (
- Paths and imports:
- Absolute and relative paths
- Using
use
statements - Re-exporting with
pub use
- Import grouping and nesting
- The
super
andcrate
keywords - The 2018 module system
- Comparing with JavaScript/TypeScript modules
Resources
Use Cases
- Organizing code in a logical manner
- Controlling the public API of your code
- Preventing access to implementation details
- Creating maintainable project structures
- Managing code dependencies
Day 4-7: Creating Libraries and Documentation
Topics
- Library crates vs binary crates
- Creating a library crate
- Publishing to crates.io:
- Package metadata
- Versioning
- Documentation
- License
- Documentation comments:
- Inner documentation (
//!
) - Outer documentation (
///
) - Markdown in documentation
- Doc tests
- Example code
- Inner documentation (
- Workspace management:
- Setting up a workspace
- Sharing dependencies
- Testing:
- Unit tests
- Integration tests
- Organizing test code
Resources
- Cargo Book: Publishing
- Rust By Example: Documentation
- Rust By Example: Testing
- Rust API Guidelines
- Rust Crates.io Guide
Use Cases
- Creating reusable components
- Building and sharing libraries
- Documenting code for others (and future you)
- Setting up large multi-package projects
- Testing code effectively
Exercises
- Refactor a simple program into multiple modules
- Create a small library crate with a well-defined API
- Document a library using doc comments and generate documentation
- Set up a workspace with multiple related crates
- Write both unit and integration tests for a library
- Create a binary that uses your library crate
Advanced Challenges
- Design and implement a library with a well-thought-out API
- Create a workspace with shared code between a library and binary
- Implement comprehensive documentation with examples and doc tests
- Prepare a crate for publishing (without actually publishing)
Next Steps
After completing Week 6, you’ll have mastered the basics of Rust and be ready to move to intermediate topics. Week 7 will begin the intermediate phase by exploring generics and traits, which are the foundation of Rust’s powerful type system.