Lesson 11 of 50 · rust
Slices
Duration: 12 minutes
Lesson 11 of 50 · rust
Duration: 12 minutes
rust\nfn main() {\n let arr = [1, 2, 3, 4, 5];\n let slice = &arr[1..4]; // [2, 3, 4]\n println!(\"Slice: {:?}\", slice);\n \n let all = &arr[..]; // Entire array\n let first_two = &arr[..2]; //[1, 2]\n let last_two = &arr[3..]; // [4, 5]\n}\n\n\nSlice syntax [start..end] excludes the end index (Pythonic style).\n\n## String Slices\n\nString slices (&str) are views into a String:\n\nrust\nfn main() {\n let s = String::from(\"hello world\");\n \n let hello = &s[0..5]; // \"hello\"\n let world = &s[6..11]; // \"world\"\n let entire = &s[..]; // Entire string\n \n println!(\"First word: {}\", hello);\n}\n\n\nString literals (\"hello\") are &str types.\n\n## Practical: Finding the First Word\n\nrust\nfn first_word(s: &str) -> &str {\n let bytes = s.as_bytes();\n \n for (i, &item) in bytes.iter().enumerate() {\n if item == b' ' {\n return &s[0..i];\n }\n }\n \n &s[..]\n}\n\nfn main() {\n let s = String::from(\"hello world\");\n let word = first_word(&s);\n println!(\"First word: {}\", word); // \"hello\"\n}\n\n\n## Important Type Insight\n\nrust\nlet s = String::from(\"hello\");\nlet slice: &str = &s[0..5]; // &str is a slice\nlet literal: &str = \"world\"; // Literal is also &str\n\n\nBoth are &str—Rust treats string literals as slices of static data.\n\n## Slice Benefits\n\n1. No copying: Views into existing data\n2. Type safety: Can't create invalid indices at compile time\n3. Ergonomic: Enables functions to accept both String and &str\n\nrust\nfn analyze(s: &str) { // Works with String and string literals\n println!(\"Length: {}\", s.len());\n}\n\nlet my_string = String::from(\"hello\");\nanalyze(&my_string); // String reference (coerces to &str)\nanalyze(\"world\"); // String literal\n