Why does Rust's `std::fs::File::open` take `P: AsRef<Path>`, and when is `AsRef<str>` worth it over `&str`?
answer
- cheap reference-to-reference view
- str does not deref to Path
- the conversion moves into the callee
- by-value generics consume owned args
basics
~20 sAsRef<Path> lets File::open accept &str, String, &Path, PathBuf and OsString, and as_ref() turns each into a &Path cheaply; deref coercion cannot turn a &str into a &Path. AsRef<str> pays off only when callers pass owned strings by value.
solid answer
~30 s`File::open` is `pub fn open<P: AsRef<Path>>(path: P)` and calls `path.as_ref()`. `AsRef<T>` is a cheap reference-to-reference conversion that must not fail, and std implements `AsRef<Path>` for `str`, `String`, `OsStr`, `OsString`, `Path` and `PathBuf`, so `File::open("data.toml")` works. A `&Path` parameter would reject that literal: `&str` is not a deref coercion away from `&Path`. For strings the gain is smaller, because `&String` already deref-coerces to `&str`; `S: AsRef<str>` additionally accepts owned values like `String`, `Box<str>` or `Cow<str>` by value, at the cost of moving them and of one monomorphized copy per argument type.
code
rust · 19 linesuse std::path::{Path, PathBuf};
// Accepts &str, String, &Path, PathBuf, &OsStr ... without taking a copy.
fn config_path<P: AsRef<Path>>(dir: P) -> PathBuf {
dir.as_ref().join("app.toml")
}
fn shout<S: AsRef<str>>(s: S) -> String {
s.as_ref().to_uppercase()
}
fn main() {
let owned = String::from("/etc/app");
println!("{}", config_path("/etc/app").display());
println!("{}", config_path(&owned).display());
println!("{}", config_path(PathBuf::from("/opt/app")).display());
println!("{}", config_path(Path::new("/srv")).display());
println!("{} {}", shout("hi"), shout(owned)); // owned is moved here
}go deeper
Recall that AsRef lends a cheap reference view, and that std's path functions take AsRef<Path> so string literals work.
Explain why &str does not coerce to &Path, how AsRef auto-dereferences through references, and why a by-value AsRef argument is moved.
Choose between &str, AsRef<str> and Into<String> by whether the function reads or stores, and keep generic shells thin to limit code size.
Set a team convention for public API parameters so signatures stay consistent: borrowed views for readers, Into for stored values, AsRef where std types demand it.
## What AsRef promises `AsRef<T>` lives in `core::convert` next to `From`: ```rust pub trait AsRef<T: ?Sized> { fn as_ref(&self) -> &T; } ``` Its documentation sets the contract: - It is for **cheap reference-to-reference conversions**. A costly conversion should be a `From` impl or a named function instead. - It **must not fail**; a fallible view belongs in a method returning `Option` or `Result`. - It **auto-dereferences through `&` and `&mut`**: if `T: AsRef<U>`, then `&T` and `&mut T` implement `AsRef<U>` too, which is why passing `&owned` works. `AsMut<T>` is the mutable twin, `fn as_mut(&mut self) -> &mut T`, used for parameters such as "anything I can write bytes into" (`AsMut<[u8]>`). ## Why File::open takes AsRef<Path> The standard library's file APIs are generic: `pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File>`, whose body is `OpenOptions::new().read(true).open(path.as_ref())`. In `std/src/path.rs` the library implements `AsRef<Path>` for `str`, `String`, `OsStr`, `OsString`, `Cow<'_, OsStr>`, `Path` and `PathBuf`, among others. Every one of these calls compiles: 1. `File::open("config.toml")` — a `&'static str` 2. `File::open(&name)` where `name: String` 3. `File::open(dir.join("app.toml"))` — a `PathBuf` by value 4. `File::open(Path::new("/srv"))` — a `&Path` The key point is that **`&str` does not coerce to `&Path`**. Deref coercion only follows `Deref` impls, and `str` has none targeting `Path`; the two are different types that happen to share a representation. A function written as `fn open(p: &Path)` would force every caller to write `Path::new(...)`. `AsRef<Path>` moves that conversion into the callee, once. ## AsRef<str> compared with &str For strings the picture differs, because `String: Deref<Target = str>`. A plain `&str` parameter already accepts `&String` through deref coercion. | Parameter | `"lit"` | `&owned_string` | `owned_string` by value | `Box<str>` / `Cow<str>` by value | |---|---|---|---|---| | `s: &str` | yes | yes, deref coercion | no | no | | `s: impl AsRef<str>` | yes | yes | yes, and it is moved | yes | | `s: impl Into<String>` | yes, allocates | yes, clones | yes, no copy | yes | So `impl AsRef<str>` is worth it in a generic helper that callers feed with assorted owned string types. When the function only reads text and callers can write `&x`, `&str` is simpler and compiles once. When the function will **store** the string, `impl Into<String>` avoids copying an owned argument — that is a different trait answering a different question. ## The costs of a generic AsRef parameter - **Moves.** `shout(owned)` with `S: AsRef<str>` takes `owned` by value; using `owned` afterwards is E0382. Callers who want to keep it pass `&owned`. - **Code size.** Each distinct argument type creates another instantiation of the function. `std::fs::read` and similar functions keep the generic shell tiny and forward to an inner non-generic `fn inner(path: &Path)`, a pattern explained with monomorphization. ## AsMut for writable views `AsMut` follows the same pattern for mutation. A helper such as `fn fill<B: AsMut<[u8]>>(mut buf: B) -> B` can zero or fill: - a `Vec<u8>` passed by value and handed back, - a fixed array `[u8; 3]`, which implements `AsMut<[u8]>`, - a `&mut [u8]` borrowed from elsewhere, through the blanket impl for `&mut T`. The rules mirror `AsRef`: the conversion is cheap, must not fail, and auto-dereferences only through `&mut`. Reach for it when a function writes into a buffer and should not care which container owns the bytes. ## Edges of AsRef - **It is not reflexive in general.** There is no `impl<T> AsRef<T> for T`: the documentation explains it would overlap with the blanket impl for references. `str: AsRef<str>` and `Path: AsRef<Path>` exist because std wrote them one by one. - **It does not see through every smart pointer.** `Box<String>` does not implement `AsRef<str>` (rustc 1.99 reports E0277); `Box<T>: AsRef<T>` lends the `String`, one level only. - **It is not a dereference shortcut.** The docs advise against calling `as_ref()` merely to get from `Box<i32>` to `&i32`; write `&x` and let deref coercion do it. - **A field view is fine.** A `User` may implement `AsRef<str>` to lend its name, because `AsRef` carries no requirement that the view compare or hash like the whole value.
- Why can't a function taking `&Path` accept the literal `"data.toml"` directly?Deref coercion only follows `Deref` impls, and `str` has no `Deref` to `Path`. The caller must write `Path::new("data.toml")`. A `P: AsRef<Path>` parameter performs that cheap conversion inside the function, so callers can pass the literal.
- Does `Box<String>` satisfy an `AsRef<str>` bound?No; rustc 1.99 reports E0277. `AsRef` auto-dereferences only through `&` and `&mut`, and `Box<T>: AsRef<T>` lends a `&String`, not a `&str`. Pass `b.as_str()` or `&**b`, or change the bound.
- When would you take `impl Into<String>` instead of `impl AsRef<str>`?When the function keeps the string, for example storing a name in a struct. `Into<String>` moves an owned `String` in without copying and allocates only for a `&str`; `AsRef<str>` would force a fresh allocation even when the caller handed over an owned `String`.
- &str and impl AsRef<str> parameters accept exactly the same arguments.
- as_ref() may allocate a new value of the target type.
- Every type T implements AsRef<T> through a blanket impl.
- A &str coerces to &Path, so AsRef<Path> parameters add nothing.
- AsRef<str> sees through Box, so Box<String> satisfies it.