Creating a String
- Rust course
- Beginner
- Lesson 20/115
- 4 min
Learn String::new, String::from and to_string constructors.
Creating Strings
There are several equivalent ways to create a String:
let a = String::new(); // empty
let b = String::from("Rust");
let c = "Rust".to_string();
let d: String = "Rust".into();
let e = 42.to_string(); // number to textto_string works on every type that implements Display. If the size is known, String::with_capacity(n) avoids repeated allocations.
Going between String and &str
Getting a &str from a String is cheap (no copy): &s, s.as_str() or &s[..]. Making a String from a &str allocates new memory (to_string, to_owned). That's why working with &str is more efficient unless you need to store the value.
Practice Build text
Create let mut s = String::with_capacity(16);. Add s.push_str("Yıl: "); and s.push_str(&2026.to_string());; print s and s.len().
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let mut s = String::with_capacity(16);
s.push_str("Yıl: ");
s.push_str(&2026.to_string());
println!("{} {}", s, s.len());
}Expected output
Yıl: 2026 10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the difference between <code>String::from("a")</code> and <code>"a".to_string()</code>?
- from is immutable
- The result is the same; both create a new String Correct answer
- to_string returns a &str
- from is slower
Explanation: Both produce an owned String on the heap; which to use is mostly a matter of taste.
2 Number to text
let s = 2026.____();
println!("{}", s.len()); // 4
let s = 2026.to_string();
println!("{}", s.len()); // 4
Explanation: to_string produces a String from a value that implements Display.
3 Expression and result
| Term | Meaning |
|---|---|
String::new() |
An empty String |
"a".to_string() |
A new String |
s.as_str() |
&str (no copy) |
42.to_string() |
"42" |