capypad
0 day streak
rust / beginner
Snippet

Understanding String vs &str in Rust

Rust has two main string types: owned String and borrowed string slices (&str). String is heap-allocated and growable, while &str is a reference to string data (either borrowed or stored in the binary). Functions accepting &str are more flexible since they work with both types.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
fn print_greeting(message: &str) {
println!("Hello, {}!", message);
}
 
fn main() {
let owned = String::from("World");
print_greeting(&owned);
let literal = "Rustacean";
print_greeting(literal);
}
Breakdown
1
fn print_greeting(message: &str)
Function that accepts any string-like reference, very flexible
2
let owned = String::from("World");
Creates a heap-allocated String, owns the data
3
print_greeting(&owned);
Passes a reference to the owned String
4
let literal = "Rustacean";
String literal stored in the program binary
5
print_greeting(literal);
Passes the string slice directly