SlicesAdvanced
1Question 1 of 1
rustWhat are Slices in Rust and how do they avoid memory copies?
Explanation & Concept
A slice is a two-word reference to a contiguous sequence of elements in a collection, consisting of a pointer to the start and a length.
`&str` is a string slice pointing to UTF-8 bytes, and `&[T]` is a generic array slice. They allow viewing subsections of arrays or strings without cloning.
Code Example
rust
fn main() {
let text = String::from("hello world");
let word1: &str = &text[0..5]; // "hello"
let word2: &str = &text[6..11]; // "world"
println!("Slice 1: {}, Slice 2: {}", word1, word2);
}How It Works & Key Takeaways
Slices prevent unnecessary heap copies when passing sub-ranges to functions.
Mock Test · 1 Questions · Optional
Ready for Async Rust?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions