In this tutorial, you’ll Learn the difference between String and &str, and when to use each.
Two Ways to Represent Text #
In Rust, text comes in two main forms:
String→ an owned, growable, heap-allocated string.&str→ a string slice, borrowed from somewhere else.
Think of it like this:
String= you own the whole book 📖.&str= you borrow a page from that book 📄.
The String Type #
- Stored on the heap
- Growable (you can push more text)
- Used when you need ownership of the string
For example:
fn main() {
let mut s = String::from("Hello"); // create a String
s.push_str(", world!"); // add more text
println!("{}", s); // "Hello, world!"
}Code language: Rust (rust)Output:
Hello, world!Code language: Rust (rust)You use String when you need to store, modify, or transfer ownership of text.
The &str Type (String Slice) #
- A view into a string, not owned
- Usually references string literals (
"text") or parts of aString - Cheap to copy, because it’s just a pointer + length
For example:
fn main() {
let greeting: &str = "Hello, world!"; // string literal
println!("{}", greeting);
let s = String::from("Good morning");
let slice: &str = &s[0..4]; // borrow a slice ("Good")
println!("{}", slice);
}
Code language: Rust (rust)Output:
Hello, world!
GoodCode language: Rust (rust)You use &str when you just need to read text without taking ownership.
Converting Between String and &str #
String → &str: easy, just borrow with&&str → String: use.to_string()orString::from
For example:
fn main() {
let s = String::from("Hello");
// String -> &str
print_str(&s);
// &str -> String
let slice = "world";
let owned: String = slice.to_string();
println!("{}", owned);
}
fn print_str(text: &str) {
println!("Text: {}", text);
}
Code language: Rust (rust)When to Use Which? #
- Use
Stringwhen:- You need ownership of the text.
- You want to store it in a struct.
- You’ll be modifying the text (adding, removing, etc).
- Use
&strwhen:- You only need to read the text.
- You want to accept both string literals and
Strings in a function. - You don’t want to copy or allocate memory unnecessarily.
Summary #
String= owned, heap-allocated, mutable.&str= borrowed, immutable slice of a string.- Conversions are straightforward:
&s→&str"text".to_string()→String
Rust’s design ensures you always know who owns the text and how long it lives.
Was this Helpful ?