Rust Design Patterns
Use borrowed types for arguments
By using the target type of deref coercion as a function argument, you can accept many different types.
-
&String
->&str
-
&Vec<T>
->&[T]
-
&Box<T>
->&T
Deref coercion:
A mechanism that automatically converts certain reference types and smart pointer types into other reference types.
Why should we use borrowed types?
Using borrowed types rather than borrowing owned types avoids extra layers of intermediate references.
fn contains_three_vowels(word: &str) -> bool {
// ...
}
let s = String::from("Ferris");
contains_three_vowels(&s); // OK
contains_three_vowels("Ferris"); // OK
Concatenating Strings with format!
Using format!
is more concise and readable than using push
or push_str
on a mutable String
.
Top comments (0)