String::as_str¶
Level: reference · for working programmers
One line: Borrows the whole String as a &str — usually unnecessary, because deref coercion does it for you.
Stable since 1.7.0. Usable in a const context.
&*s, &s[..] and s.as_str() are the same borrow; and passing &s to a function expecting &str needs none of them, because deref coercion inserts it.
Where it is genuinely useful is where coercion does not fire:
- turbofish and generics —
Some(s).map(String::as_str)is tidier than a closure - type inference dead ends — comparing against a
&strin amatch, or in an iterator chain where the compiler has nothing to coerce toward - readability — making the borrow visible at a call site that is otherwise ambiguous
Free, const, and the returned view borrows the string for as long as it lives.
Example¶
string_as_str.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn shout(s: &str) -> String { s.to_uppercase() }
fn main() {
let s = String::from("hello");
// All the same borrow.
println!("{:?} {:?} {:?}", s.as_str(), &s[..], &*s);
// Deref coercion means the call needs none of them.
println!("{:?}", shout(&s));
// Where it earns its place: as a function reference.
let maybe = Some(String::from("x"));
println!("{:?}", maybe.as_deref());
let names = vec![String::from("a"), String::from("b")];
let views: Vec<&str> = names.iter().map(String::as_str).collect();
println!("{views:?}");
// Matching against string literals.
let cmd = String::from("stop");
match cmd.as_str() {
"go" => println!("going"),
"stop" => println!("stopping"),
other => println!("unknown {other:?}"),
}
}
Verified output of string_as_str.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
String::as_mut_str— the mutable versionString::as_bytes— the bytes rather than the textstr::len— one of the methods this reachesString::into_boxed_str— giving up ownership instead of borrowing
String::as_str in the standard library ↗
Po polsku¶
W codziennym kodzie as_str jest zwykle zbędne: s.as_str(), &s[..] i &*s to dokładnie to samo pożyczenie, a przekazując &s do funkcji oczekującej &str nie potrzebujesz żadnego z nich — automatyczna dereferencja (deref coercion) wstawia je za ciebie, co widać na wywołaniu shout(&s). Sięgasz po tę metodę dopiero tam, gdzie konwersja nie ma się na czym oprzeć, i najczęściej po raz pierwszy w matchu: match cmd { "stop" => … } na String kończy się błędem E0308, bo wzorzec jest literałem &str, a match cmd.as_str() dopasowuje się bez problemu. Drugi typowy przypadek to przekazanie metody jako funkcji — names.iter().map(String::as_str) czyta się lepiej niż domknięcie robiące to samo. Wynik jest darmowy, const i pożyczony, więc żyje dokładnie tak długo jak String, z którego pochodzi.
Szukaj po polsku: dopasowanie wzorców do łańcucha znaków · automatyczna dereferencja · rust match on String E0308 · rust String as_str deref coercion