codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🦀

Rust

16 / 58 topics
13Ownership14Borrowing15References16Slices
Tutorials/Rust/Slices
🦀Rust

Slices

Updated 2026-05-15
10 min read

Slices

Introduction

In Rust, a slice is a reference to a contiguous sequence of elements in a collection. Unlike vectors or arrays, slices do not own the data they point to; instead, they borrow it from another data structure. This borrowing mechanism aligns with Rust's ownership model, ensuring memory safety and preventing data races.

Slices are incredibly useful for working with parts of collections without taking ownership of them. They come in two flavors: string slices (&str) and other slices (e.g., &[T]), where T is the type of elements in the collection.

Concept

A slice is defined by a pointer to the first element and a length indicating how many elements are in the slice. This makes slices flexible and efficient, as they can be used to represent any contiguous subsequence of a collection without copying data.

String Slices

String slices (&str) are references to parts of a String or string literals. They are commonly used for function parameters that need to accept both owned strings and string slices.

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[..]
}

### Other Slices

Slices can be used with any collection that implements the `Deref` trait. For example, you can create a slice of an array or vector:

```rust
fn main() {
    let a = [1, 2, 3, 4, 5];
    let slice = &a[1..3];

    assert_eq!(slice, &[2, 3]);
}

## Examples

### String Slices in Action

Let's explore how string slices can be used in practice. Consider a function that takes a string and returns the first word:

```rust
fn main() {
    let s = String::from("Hello, world!");
    let word = first_word(&s);
    println!("The first word is: {}", 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[..]
}

In this example, `first_word` takes a string slice (`&str`) and returns another string slice. This allows the function to work with both owned strings and string literals without copying data.

### Slices with Vectors

Slices can also be used with vectors. Here's an example that demonstrates how to create and use slices of vectors:

```rust
fn main() {
    let v = vec![1, 2, 3, 4, 5];
    let slice = &v[1..3];

    assert_eq!(slice, &[2, 3]);
}

In this example, slice is a reference to the elements at indices 1 and 2 of the vector v. The slice does not own the data; it borrows it from the vector.

Mutable Slices

Slices can also be mutable. Here's an example that demonstrates how to create and use mutable slices:

fn main() {
    let mut v = vec![1, 2, 3, 4, 5];
    let slice = &mut v[1..3];

    slice[0] = 10;
    slice[1] = 20;

    assert_eq!(v, vec![1, 10, 20, 4, 5]);
}

In this example, slice is a mutable reference to the elements at indices 1 and 2 of the vector v. We can modify the elements in the slice, which will affect the original vector.

What's Next?

Now that you have a solid understanding of slices, the next topic is Structs. Structs allow you to define custom data types with named fields, making your code more organized and expressive. Stay tuned for the next section!


PreviousReferencesNext Structs

Recommended Gear

ReferencesStructs