String vs str
String is your own growable notebook of text, while &str is just a quick peek at text someone else owns.In this page:
Creating a String
String::from() or .to_string() creates an owned, growable string on the heap that you can modify and that will be cleaned up automatically when it goes out of scope.
Example: Creating a String
fn main() {
let owned = String::from("Hello");
println!("{}", owned);
}
Login to try C/C++/Java/PHP code in the editor
Growing a String
Because String owns its data, it can grow by appending more text with methods like .push_str(), something a plain &str cannot do.
Example: Growing a String
fn main() {
let mut message = String::from("Hello");
message.push_str(", Rust!");
println!("{}", message);
}
Login to try C/C++/Java/PHP code in the editor
Converting Between String and &str
You can borrow a String as a &str with &owned (or .as_str()), and convert a &str into an owned String with .to_string() or String::from().
Example: Converting Between String and &str
fn main() {
let owned: String = String::from("borrowed view");
let borrowed: &str = &owned;
println!("{}", borrowed);
let back_to_owned: String = borrowed.to_string();
println!("{}", back_to_owned);
}
Login to try C/C++/Java/PHP code in the editor
Choosing Function Parameter Types
Accepting &str in a function lets it work with both string literals and borrowed String values, making it more flexible than requiring an owned String parameter.
Example: Choosing Function Parameter Types
fn shout(text: &str) -> String {
format!("{}!!!", text.to_uppercase())
}
fn main() {
let owned = String::from("hello");
println!("{}", shout(&owned));
println!("{}", shout("literal"));
}
Login to try C/C++/Java/PHP code in the editor
- Trying to use
+=to grow a&strdirectly -- only an owned, mutableStringcan be appended to. - Forgetting that
String::from()allocates on the heap, while a&strliteral is embedded directly in the binary. - Using
Stringas a function parameter type when&strwould accept both owned strings and literals more flexibly.
Stringis an owned, growable, heap-allocated text buffer.&stris a borrowed, immutable view into string data, either from aStringor a literal..to_string()orString::from()converts a&strinto an ownedString.- Prefer
&strfor function parameters that only need to read text, andStringwhen you need to own or grow the text.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: