String and &str conversion
- Rust course
- Beginner
- Lesson 100/115
- 4 min
Learn conversion methods between String and &str.
Converting between String and &str
String is owned, growable text; &str is a borrowed view of text. Conversions:
let a: String = String::from("rust");
let b: String = "rust".to_string();
let c: String = "rust".to_owned();
let d: &str = &a; // deref coercion
let e: &str = a.as_str();
let f: String = format!("{a}-{}", 2024);Going from &str to String allocates new memory; the reverse is free.
Concatenation
The + operator takes ownership of the String on the left and needs a &str on the right:
let a = String::from("Merhaba");
let b = String::from("dünya");
let c = a + " " + &b; // a was moved, b was lent
// println!("{a}"); // error: a was moved
println!("{c} {b}");When joining several pieces, format! is more readable and moves no value. To append to an existing String, use push_str.
Practice Two calls
Write fn selamla(ad: &str) -> String returning format!("Merhaba {ad}"). Call it with a String (&s) and with a literal ("Can"); print the results separated by |.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn selamla(ad: &str) -> String {
format!("Merhaba {ad}")
}
fn main() {
let s = String::from("Ada");
println!("{}|{}", selamla(&s), selamla("Can"));
}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, what should the parameter type be?
- &str Correct answer
- String
- &String
- &mut String
Explanation: &str accepts both Strings (via &s) and literals; &String accepts only Strings.
2 Take a borrowed slice
let a = String::from("rust");
let e: &str = a.____();
let a = String::from("rust");
let e: &str = a.as_str();
Explanation: as_str views the String's content as &str without copying.
3 Expression and result type
| Term | Meaning |
|---|---|
"a".to_string() |
String |
s.as_str() |
&str |
format!("{x}") |
String (new) |
a + &b |
String (a is moved) |