&str vs String
- Rust course
- Beginner
- Lesson 19/115
- 4 min
Learn the difference and use cases of &str and String.
&str vs String
Rust has two main text types. &str (a string slice) is an immutable view that borrows UTF-8 bytes living elsewhere. String is owned, growable text on the heap.
let sabit: &str = "merhaba"; // embedded in the program
let mut sahip: String = String::from("merhaba");
sahip.push_str(" dünya"); // a String can growFunction parameters usually take &str; it accepts both &String and string literals.
The ownership difference
When a String is assigned to another variable, ownership moves and the old variable can't be used; a &str is a copyable reference:
let a = String::from("Go");
let b = a; // ownership moved to b
// println!("{a}"); // compile error: a was moved
let s1 = "Rust";
let s2 = s1; // &str is copied, both are usableThis rule is covered in detail in the ownership lesson.
Practice Greet
Let fn selam(ad: &str) -> String return format!("Merhaba {ad}"). Call it with both selam("Ada") and let s = String::from("Can"); selam(&s) and print both results.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn selam(ad: &str) -> String {
format!("Merhaba {ad}")
}
fn main() {
let s = String::from("Can");
println!("{}", selam("Ada"));
println!("{}", selam(&s));
}Expected output
Merhaba Ada Merhaba Can
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If a function only reads text, which parameter type is most flexible?
- &mut String
- Vec<char>
- &str Correct answer
- String
Explanation: &String converts to &str automatically (deref coercion); taking a String would force the caller to give up ownership.
2 Owned text
let mut ad = ____::from("Ada");
ad.push_str(" Lovelace");
let mut ad = String::from("Ada");
ad.push_str(" Lovelace");
Explanation: String::from creates an owned, growable String from a &str.
3 Type and property
| Term | Meaning |
|---|---|
&str |
Borrowed, immutable |
String |
Owned, grows |
"metin" |
&'static str |
&String → &str |
Automatic conversion |