Sub topic 9
Accepting &str in Functions and Deref Coercion
This chapter assumes you know basic Rust syntax, ownership and borrowing, and how String differs from &str. You will learn which string type to put in a function signature and why callers rarely need to convert anything.
Why `&str` is the default for read-only parameters
If a function only reads text, it does not need to own it. Taking &str lets the caller pass a string literal, a borrowed String, or a slice of either. Taking String forces the caller to give up ownership or clone.
fn shout(s: &str) -> String {
s.to_uppercase()
}
fn main() {
let owned = String::from("hi");
println!("{}", shout(&owned));
println!("{}", shout("there"));
}The call shout(&owned) passes a &String, yet the parameter type is &str. This compiles because of deref coercion.
What deref coercion does
String implements the Deref trait with Target = str. When the compiler expects &str and sees &String, it inserts a call to deref for you. This happens at coercion sites, such as function arguments, and costs nothing at run time. It only changes how the same bytes are viewed.
The compiler can apply the step repeatedly. A &&String or a &Box<String> also coerces to &str.
Choosing the parameter type
| Situation | Parameter type | Reason |
|---|---|---|
| Function only reads text | `&str` | Accepts literals, `&String`, and slices |
| Function stores the text or must own it | `String` | Caller decides whether to move or clone |
| Function needs to modify the caller's string | `&mut String` | `&mut str` cannot grow or shrink |
| Function accepts many string-like types | `impl AsRef<str>` or `impl Into<String>` | Flexible, but adds generics |
Avoid &String as a parameter type. It is strictly less flexible than &str, because a literal cannot be passed where &String is required.
fn takes_string_ref(s: &String) -> usize {
s.len()
}
fn takes_str(s: &str) -> usize {
s.len()
}
fn main() {
let owned = String::from("hello");
println!("{}", takes_string_ref(&owned));
println!("{}", takes_str(&owned));
println!("{}", takes_str("hello"));
// takes_string_ref("hello"); // error: expected `&String`, found `&str`
}Returning strings
Return String when the function builds new text. Return &str only when the result borrows from an input, and then the lifetime must connect them.
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let sentence = String::from("borrow checker rocks");
let word = first_word(&sentence);
println!("{word}");
}Lifetime elision gives first_word the signature fn first_word<'a>(s: &'a str) -> &'a str. The returned slice cannot outlive sentence.
When the function needs ownership
If the function stores the text in a struct, take String or impl Into<String>. The caller can then pass an owned value without a copy.
struct User {
name: String,
}
impl User {
fn new(name: impl Into<String>) -> Self {
User { name: name.into() }
}
}
fn main() {
let a = User::new("Ada");
let b = User::new(String::from("Grace"));
println!("{} {}", a.name, b.name);
}A &str argument allocates once inside into. A String argument moves in with no allocation.
Common errors
- Writing
fn f(s: &String)and then failing to call it with a literal. - Returning
&strthat borrows from a localString, which the borrow checker rejects with "returns a reference to data owned by the current function". - Expecting coercion from
&strto&String. Coercion goes only from owned to borrowed, never back.
Exercise
A function fn count_vowels(s: &String) -> usize is called as count_vowels("banana"), and it fails to compile. Change the signature so that it accepts both a literal and a String borrowed with &. Explain why the new signature works for the second case.
Show answer
Change the parameter to s: &str. A literal already has type &str. For a String passed as &owned, the compiler applies deref coercion from &String to &str because String implements Deref<Target = str>.