IntoIterator Consumes Custom Collection

Implement IntoIterator for a custom collection so for loops consume it: items move out one by one and the original struct is gone after the loop.

RustData Integrity

Code

rustsnippet
26 lines
// 自定义集合实现 IntoIterator:for 循环就能直接消耗它
struct Playlist {
    tracks: Vec<String>,
}

impl IntoIterator for Playlist {
    type Item = String;
    type IntoIter = std::vec::IntoIter<String>;

    fn into_iter(self) -> Self::IntoIter {
        self.tracks.into_iter()
    }
}

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

    // for 循环背后调用 into_iter:所有权移入循环,元素逐个移出
    for track in playlist {
        println!("playing: {track}");
    }
    // 取消注释无法编译:playlist 已被消耗
    // println!("{}", playlist.tracks.len());
}

How it works

IntoIterator Consumes Custom Collection is built around the functions into_iter and main.

Repetition is confined to for track in playlist — the rest of the file is straight-line.

Using it

Signature: fn into_iter(self) -> Self::IntoIter

The demo output is labeled (playing:), so every printed line maps back to its originating operation.

Key statements

fn into_iter(self) -> Self::IntoIter {
self.tracks.into_iter()
}

Interactive Tools for This Topic

FAQ

What does IntoIterator Consumes Custom Collection print when run?
Invoke the file as-is — the `playing:` prefixes identify which step printed each line.