17.4 Prelude and Common Imports
17.4.1 What Is the Prelude?
The prelude is a set of standard library items automatically imported into every module. This includes types like Option
and Result
and traits like Copy
, Clone
, and ToString
.
This saves you from needing to import these items explicitly in every module.
17.4.2 Explicit Imports and use
While the prelude covers common items, you often need to import other items explicitly using use
. This makes dependencies clear and code more readable.
Example:
use std::fs::File;
use std::io::{self, Read};
fn read_file() -> io::Result<String> {
let mut file = File::open("data.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}