Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Slices | Rust Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Rust Fundamentals

Lesson 11 of 50

·rust

Slices

12 minutes

Course progress22%

Slices

Slices are views into a contiguous sequence without owning the data. They're references to a portion of a collection.

Array Slices

fn main() {
    let arr = [1, 2, 3, 4, 5];
      = &arr[..];  
    (\
let
slice
1
4
// [2, 3, 4]
println!
"Slice: {:?}\", slice); let all = &arr[..]; // Entire array let first_two = &arr[..2]; //[1, 2] let last_two = &arr[3..]; // [4, 5] }

Slice syntax [start..end] excludes the end index (Pythonic style).

String Slices

String slices (&str) are views into a String:

fn main() {
    let s = String::from(\"hello world\");
    
    let hello = &s[0..5];    // \"hello\"
    let world = &s[6..11];   // \"world\"
    let entire = &s[..];     // Entire string
    
    println!(\"First word: {}\", hello);
}

String literals (\"hello\") are &str types.

Practical: Finding the First Word

fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();
    
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    
    &s[..]
}

fn main() {
    let s = String::from(\"hello world\");
    let word = first_word(&s);
    println!(\"First word: {}\", word);  // \"hello\"
}

Important Type Insight

let s = String::from(\"hello\");
let slice: &str = &s[0..5];    // &str is a slice
let literal: &str = \"world\";    // Literal is also &str

Both are &str—Rust treats string literals as slices of static data.

Slice Benefits

  1. No copying: Views into existing data
  2. Type safety: Can't create invalid indices at compile time
  3. Ergonomic: Enables functions to accept both String and &str
fn analyze(s: &str) {  // Works with String and string literals
    println!(\"Length: {}\", s.len());
}

let my_string = String::from(\"hello\");
analyze(&my_string);       // String reference (coerces to &str)
analyze(\"world\");          // String literal
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities
Previous lessonBorrowing and ReferencesContinue to lesson 12StringsBack to Rust Fundamentals curriculum