2.17 Additional Topics
Rust offers many more features, the most important of which are covered in subsequent chapters.
2.17.1 The Standard Library
Rust’s standard library provides data structures (such as Vec
and HashMap
), I/O utilities, threading support, and more—similar to C’s standard library, but generally more extensive.
2.17.2 Testing
Rust has built-in testing:
#![allow(unused)] fn main() { #[cfg(test)] mod tests { #[test] fn test_add() { assert_eq!(2 + 2, 4); } } }
You can run tests with cargo test
. Rust also supports separate test files in a tests
folder and can test code blocks inside documentation comments.
2.17.3 Cargo Features
- Build:
cargo build
- Run:
cargo run
- Test:
cargo test
- Generate Docs:
cargo doc --open
2.17.4 Error Messages and Tooling
rustc
provides detailed error messages.clippy
lints for style issues and common mistakes.
2.17.5 Arrays, Structs, and Enums
Like C, Rust has arrays and structs to group homogeneous or heterogeneous data. However, while C’s enums are essentially named integers, Rust’s enums can also serve as a safer alternative to C’s unions, storing different variants without losing type information.
2.17.6 Unsafe Rust
Rust allows the use of unsafe
code blocks, granting access to features that bypass some of the language’s safety guarantees. These include operations such as working with raw pointers, which are not subject to Rust’s strict borrowing rules.
2.17.7 Concurrency
Rust supports safe, efficient concurrency and parallel execution. Its ownership system, combined with the Send
and Sync
traits, ensures that data races are eliminated at compile time. The standard library provides multi-threading primitives, such as std::thread
for spawning threads, and crates like Rayon and Crossbeam offer parallel iterators and thread pools for advanced concurrency patterns.
2.17.8 Asynchronous Programming
Rust supports asynchronous programming through the async
and await
keywords. You can write functions that return async
blocks and use runtime crates (such as tokio
or async-std
) to execute asynchronous tasks efficiently. This model leverages Rust’s ownership and type system to prevent data races, providing a safe alternative to manually handling threads.