beginnerCompound Types
String and &str
Difference between String and string slices (&str).
String and &str
Difference between String and string slices (&str).
Difficulty
Beginner
Code
rust
fn greet(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
let s1: &str = "string literal";
let s2: String = String::from("owned string");
let s3: &str = &s2[..6];
greet(s1);
greet(&s2);
println!("slice: {}", s3);
}Explanation
This example demonstrates how to use string and &str in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the compound-types category to build a complete understanding of this topic.