← Back to Rust Course | Chapter 6: Borrowing & References | Lesson 6 of 6

String Slices

A string slice is a peek at part of some text, borrowed instead of copied, so it's quick and doesn't waste memory.

Creating a String Slice

A string slice references part of a String's data using a byte-range index. It does not own or copy the text -- it simply points into the original string's memory.

Example: Creating a String Slice

markup
fn main() {
    let greeting = String::from("Hello, world!");
    let hello = &greeting[0..5];
    println!("{}", hello);
}

String Literals Are Slices

A string literal written directly in source code, like "Rust", has the type &str and lives for the entire duration of the program, since it is embedded directly in the compiled binary.

Example: String Literals Are Slices

markup
fn main() {
    let literal: &str = "I am already a slice";
    println!("{}", literal);
}

Accepting &str in Functions

Writing a function parameter as &str instead of String lets it accept both borrowed String data and string literals, making the function more flexible for callers.

Example: Accepting &str in Functions

markup
fn first_word(text: &str) -> &str {
    match text.find(' ') {
        Some(index) => &text[..index],
        None => text,
    }
}

fn main() {
    let sentence = String::from("Rust is fun");
    println!("{}", first_word(&sentence));
}

Slicing on Character Boundaries

Because Rust strings are UTF-8 encoded, slice indices must land on valid character boundaries. Slicing through the middle of a multi-byte character causes a runtime panic, so text-safe code often uses methods like .chars() instead of raw byte indices.

Example: Slicing on Character Boundaries

markup
fn main() {
    let word = "Rust";
    let piece = &word[0..2];
    println!("First two bytes: {}", piece);
}
Common Mistakes
  1. Trying to slice a String in the middle of a multi-byte UTF-8 character, which panics at runtime.
  2. Using String everywhere a function only needs to read text, when accepting &str would work for both owned strings and literals.
  3. Assuming &str and String are the same type -- &str is a borrowed view while String is an owned, growable buffer.
Chapter Summary
  • &str is an immutable reference to some UTF-8 text, either borrowed from a String or a string literal.
  • String slices use byte-index ranges, e.g. &text[0..5], and must fall on valid UTF-8 character boundaries.
  • String literals like "hello" are already &str slices with a 'static lifetime.
  • Functions that only need to read string data should typically accept &str rather than String for maximum flexibility.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.