capypad
0 day streak
rust / beginner
Snippet

Understanding String and &str Types

Rust has two main string types: String (owned, heap-allocated, growable) and &str (borrowed string slice pointing to existing data). Understanding this distinction is crucial for memory management and performance in Rust applications.

snippet.rs
rust
1
2
3
4
5
6
7
8
fn main() {
let owned: String = String::from("Hello");
let borrowed: &str = "World";
let combined: String = owned + ", " + borrowed;
let slice: &str = &combined[0..5];
println!("Combined: {}", combined);
println!("Slice: {}", slice);
}
Breakdown
1
String::from("Hello")
Creates an owned String allocated on the heap
2
let borrowed: &str = "World";
Creates a string slice reference pointing to static memory
3
owned + ", " + borrowed
Concatenates strings using the + operator (borrowed is coerced)