The Rust Standard Library is a comprehensive collection of core types, traits, and functions that provide essential functionality for Rust programs. It serves as the foundation for most Rust applications, offering a wide range of tools for common programming tasks.
The Rust Standard Library includes several important modules:
To use the Standard Library, simply import the desired modules or types. Most Rust programs automatically include the prelude, which brings common types and traits into scope.
use std::collections::HashMap;
use std::io::Read;
fn main() {
let mut map = HashMap::new();
map.insert("key", "value");
let mut input = String::new();
std::io::stdin().read_to_string(&mut input).unwrap();
}
The Standard Library enforces Rust's memory safety guarantees, preventing common issues like null or dangling pointer dereferences.
With modules like std::thread
and std::sync
, the library provides robust tools for concurrent programming. For more advanced concurrency patterns, consider exploring Rust Asynchronous Programming.
The Result
and Option
types offer elegant solutions for error handling and optional values. Learn more about Rust Result Enum and Rust Option Enum.
std::prelude
to avoid unnecessary imports for commonly used types.The Standard Library also provides advanced features for more complex scenarios:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
This example demonstrates thread-safe sharing of data using Arc
and Mutex
from the Standard Library.
The Rust Standard Library is an indispensable tool for Rust developers. By mastering its components, you can write efficient, safe, and idiomatic Rust code. As you progress, explore more advanced concepts like Rust Generic Types and Rust Trait Definitions to fully harness the power of Rust programming.