Deref Lets A Wrapper Act Like A Slice

A container wrapper implementing Deref and DerefMut to a slice gets indexing, len, and in-place sort for free, without exposing the inner field.

RustData Integrity

Code

rustsnippet
32 lines
use std::ops::{Deref, DerefMut};

// 包装 Vec:容器 deref 到 slice 是无争议的惯用法
struct Playlist {
    tracks: Vec<String>,
}

impl Deref for Playlist {
    type Target = [String];

    fn deref(&self) -> &[String] {
        &self.tracks
    }
}

impl DerefMut for Playlist {
    fn deref_mut(&mut self) -> &mut [String] {
        &mut self.tracks
    }
}

fn main() {
    let mut list = Playlist { tracks: vec!["intro".into(), "bridge".into(), "outro".into()] };

    // 借读:索引和 len 直接命中解引用目标,不用 .tracks 中转
    println!("first: {}", list[0]);
    println!("len: {}", list.len());

    // 借写:DerefMut 让 sort 就地生效
    list.sort();
    println!("sorted: {:?}", list[..]);
}

How it works

Deref Lets A Wrapper Act Like A Slice keeps everything in the functions deref, deref_mut and main.

Applying it

Entry signature: fn deref(&self) -> &[String]

Running the file prints labeled results such as first:, len:, sorted: — each operation’s effect is visible in the output.

Statements that matter

fn deref_mut(&mut self) -> &mut [String] {
&mut self.tracks
}
fn deref(&self) -> &[String] {
&self.tracks
}
list.sort();

Interactive Tools for This Topic

FAQ

What does Deref Lets A Wrapper Act Like A Slice print when run?
Run it as a complete program — the output lines carry labels such as `first:`, `len:`, `sorted:`.