capypad
0 day streak
rust / beginner
Snippet

String Basics: String vs &str

Rust has two main string types: String (owned, heap-allocated) and &str (borrowed string slice). String is growable and mutable, while &str is a read-only view into text. Use String when you need ownership and &str when you only need to read or borrow text.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fn main() {
// Creating a String from a string literal
let greeting: String = String::from("Hello");
// Creating a string slice reference
let slice: &str = "World";
// Pushing a string slice to a String
let mut combined = greeting;
combined.push_str(" ");
combined.push_str(slice);
// Getting the length
println!("Length: {}", combined.len());
// Checking if empty
println!("Is empty: {}", combined.is_empty());
// Converting String to &str (borrowing)
let as_str: &str = &combined;
println!("As &str: {}", as_str);
}
Breakdown
1
let greeting: String = String::from("Hello");
Creates an owned String from a string literal using the from constructor
2
let slice: &str = "World";
Creates a string slice reference pointing to static string data
3
combined.push_str(slice);
Appends a string slice to the String without taking ownership of slice
4
combined.len()
Returns the byte length of the string (not character count for UTF-8)
5
let as_str: &str = &combined;
Creates a borrowed reference to the String, converting &String to &str