Sub topic 9
Accepting &str in functions and deref coercion
This chapter assumes you know basic Rust syntax, ownership and borrowing, and the difference between &str and String from earlier chapters. It covers how to choose parameter types for text, and why &str accepts so many different arguments.
The default rule: take `&str` for read-only text
If a function only reads text, make the parameter &str. A &str is a pointer and a length into UTF-8 bytes that live somewhere else. It says nothing about who owns those bytes, so the caller can pass text from many sources.
fn shout(s: &str) -> String {
s.to_uppercase()
}
fn main() {
let owned = String::from("hi");
println!("{}", shout(&owned));
println!("{}", shout("there"));
println!("{}", shout(&owned[0..1]));
}All three calls compile, and they pass three different things:
&ownedhas type&String."there"has type&'static str.&owned[0..1]has type&str.
If shout took &String, the second and third calls would fail. A literal is not a String, and building one just to call the function would allocate for no reason.
Clippy warns about &String parameters with its ptr_arg lint. A &String gives the function no ability beyond what &str offers. You can read the length and contents, but you cannot grow the string through a shared reference. It only restricts callers.
Deref coercion: how `&String` becomes `&str`
The standard library implements the Deref trait for String with Target = str. Rust also applies a rule called deref coercion. When a reference &T is used where &U is expected, and T: Deref<Target = U>, the compiler inserts the conversion for you.
So shout(&owned) is treated as if you had written shout(&*owned). The *owned calls Deref::deref to get a str, and & borrows it again. This costs nothing at run time. It only reinterprets the same pointer and length.
Coercion applies repeatedly, so a chain of smart pointers works too:
use std::rc::Rc;
fn len_of(s: &str) -> usize {
s.len()
}
fn main() {
let a = String::from("abc");
let b = Box::new(String::from("defg"));
let c = Rc::new(String::from("hi"));
println!("{} {} {}", len_of(&a), len_of(&b), len_of(&c));
}This prints 3 4 2. The argument &b has type &Box<String>. The compiler follows Box<String> to String to str, one Deref step at a time, until the types match.
Where coercion happens
Coercion applies at "coercion sites". These are places where the expected type is known:
- Function and method call arguments.
letstatements with an explicit type, such aslet s: &str = &owned;.- Struct field initializers and return expressions, when the target type is declared.
You can also spell the conversion out when you want to. These forms are equivalent:
fn main() {
let owned = String::from("text");
let a: &str = &owned;
let b: &str = owned.as_str();
let c: &str = &owned[..];
let d: &str = &*owned;
println!("{a} {b} {c} {d}");
}as_str() is usually the clearest choice when the expected type is not known, for example inside a closure or a match arm.
Where coercion does not happen
Coercion needs a known target type. It does not apply where the expected type is a generic parameter, because the compiler would infer T = &String and see no reason to change it. It also does not convert a container of references into another container.
- A function taking
&[&str]rejects&Vec<String>. Deref coercion turns&Vec<T>into&[T], but the element type is stillString, not&str. - A
HashMap<String, V>lookup takes&QwhereString: Borrow<Q>. This is a different mechanism, which is whymap.get("key")works with a&str. - Passing a
Stringby value to a&strparameter fails. Coercion changes references only, so you must write&s.
Mutable references and `&mut str`
&mut String also coerces to &mut str through DerefMut. A &mut str can change bytes in place but cannot change the length, since it is only a view with no capacity.
fn upper_in_place(s: &mut str) {
s.make_ascii_uppercase();
}
fn add_exclaim(s: &mut String) {
s.push('!');
}
fn main() {
let mut s = String::from("abc");
upper_in_place(&mut s);
add_exclaim(&mut s);
println!("{s}");
}This prints ABC!. If a function needs to grow the text, it must take &mut String. If it only edits characters without resizing, &mut str is enough. Most in-place edits that keep the length are limited to ASCII, because many Unicode case changes alter the byte length.
Returning borrowed text
A function can return a &str that points into its input. Lifetime elision ties the output to the single input reference:
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let line = String::from("alpha beta");
println!("{}", first_word(&line));
println!("{}", first_word("gamma delta"));
}Returning a slice avoids allocating a new String. The result cannot outlive the input, so if the caller needs to keep it after dropping line, the caller calls .to_string() or .to_owned() at that point. This keeps the allocation decision with the code that knows how long the text must live.
When to take ownership instead
Use String as a parameter when the function stores the text, or sends it to another thread. If you take &str and then call .to_string() inside, callers who already own a String pay for an extra copy. If you take String, callers with a &str must allocate.
Two generic patterns let the caller choose:
struct User {
name: String,
}
impl User {
fn new(name: impl Into<String>) -> Self {
User { name: name.into() }
}
fn name(&self) -> &str {
&self.name
}
}
fn count_a<S: AsRef<str>>(s: S) -> usize {
s.as_ref().matches('a').count()
}
fn main() {
let owned = String::from("Ada");
let u1 = User::new("Grace");
let u2 = User::new(owned);
println!("{} {}", u1.name(), u2.name());
println!("{}", count_a("banana"));
println!("{}", count_a(String::from("alpha")));
}impl Into<String>suits constructors and setters. A caller passing aStringmoves it in with no copy, and a caller passing&strtriggers one allocation.AsRef<str>suits functions that only read. It accepts&str,String,&String, andBox<str>.
The generic versions have a cost. The compiler generates a separate copy of the function for each argument type, which can grow the binary. A common remedy is a thin generic wrapper that calls a non-generic inner function taking &str.
Notice also that User::name returns &str, not &String. That hides the field's concrete type, so you can later change it to Box<str> or Cow<'static, str> without breaking callers.
Choosing a parameter type
| Parameter type | Accepts | Ownership | Typical use |
|---|---|---|---|
| `&str` | literals, `&String`, slices, `&Box<String>` | borrowed | read-only processing |
| `&mut str` | `&mut String` | borrowed, no resizing | in-place ASCII edits |
| `&mut String` | `&mut String` only | borrowed, can grow | appending to the caller's buffer |
| `String` | owned `String` only | moved in | storing or sending the text |
| `impl Into<String>` | `&str`, `String`, `char`, `Box<str>` | moved or copied | constructors, setters |
| `S: AsRef<str>` | anything that views as `str` | either | flexible read-only APIs |
Common mistakes
- Writing
fn f(s: &String). Change it to&str. - Calling
.to_string()on an argument just to pass it to a function that takes&str. Borrow it instead. - Taking
Stringwhen the function only reads. This forces callers to give up or clone their value. - Expecting coercion to work through generics or inside collections such as
Vec<&str>. - Returning
&strborrowed from a localString. This does not compile, because the local is dropped at the end of the function. ReturnStringin that case.
Exercise
You write fn word_count(text: &String) -> usize. A caller has let s = "one two"; and another has let b: Box<String> = Box::new(String::from("x y z"));. Which calls compile, and how do you change the signature so both work?
Show answer
With &String, the literal call word_count(s) fails, because s is a &str. The call word_count(&b) compiles, since &Box<String> coerces to &String. Change the signature to fn word_count(text: &str) -> usize. Then word_count(s) works directly, and word_count(&b) works because &Box<String> coerces through &String to &str.
Exercise
Why does fn grow(s: &mut str) fail to support s.push('x'), and what signature fixes it?
Show answer
A str is a fixed-size view with no capacity, so it has no push method. Take &mut String instead, because String owns a growable buffer.