AsRef and AsMut for flexible function parameters

Marcus Chen Jan 2026
1 tab
use std::path::Path;

fn process_file(path: impl AsRef<Path>) {
    let path = path.as_ref();
    println!("Processing: {}", path.display());
}

fn main() {
    process_file("file.txt");
    process_file(std::path::PathBuf::from("/tmp/data"));
}
1 file · rust Explain with highlit

AsRef<T> is a trait for cheap reference-to-reference conversion. It's commonly used in function parameters to accept multiple types. For example, a function taking impl AsRef<Path> can accept &Path, PathBuf, &str, or String. This is more ergonomic than overloads or manual conversion. I use AsRef in public APIs to maximize flexibility. AsMut is the mutable equivalent. The trait is implemented by the standard library for common conversions. It's a lightweight abstraction that makes APIs user-friendly without runtime cost. Combined with &str/String or Path/PathBuf pairs, it's essential for writing idiomatic Rust libraries.