From f8281d894bf2cfcb63297bcf0a443a4868446d18 Mon Sep 17 00:00:00 2001 From: Dawid Pietrykowski Date: Tue, 20 Jun 2023 18:39:02 +0200 Subject: [PATCH] Finished implementing code with iterator --- src/main.rs | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index e7a11a9..1b921f3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,75 @@ -fn main() { - println!("Hello, world!"); +#[allow(dead_code)] +#[derive(Debug)] +struct Song { + name: String, + artist: String, + duration: f32 +} + +struct Playlist{ + songs: Vec, +} + +impl Playlist{ + fn new() -> Playlist { + Playlist{ + songs: Vec::new(), + } + } + + fn iter(&self) -> PlaylistIterator{ + PlaylistIterator{ + playlist: self, + current_index: 0 + } + } + + fn add_song(&mut self, song: Song){ + self.songs.push(song); + } +} + +struct PlaylistIterator<'a> { + playlist: &'a Playlist, + current_index: u32, +} + +impl<'a> Iterator for PlaylistIterator<'a>{ + type Item = &'a Song; + + fn next(&mut self) -> Option { + let song = self.playlist.songs.get(self.current_index as usize); + self.current_index += 1; + song + } +} + +fn main() { + let mut playlist = Playlist::new(); + + playlist.add_song( + Song{ + name: String::from("s1"), + artist: String::from("a1"), + duration: 1.2 + } + ); + playlist.add_song( + Song{ + name: String::from("s2"), + artist: String::from("a2"), + duration: 1.6 + } + ); + playlist.add_song( + Song{ + name: String::from("s3"), + artist: String::from("a3"), + duration: 2.2 + } + ); + + for song in playlist.iter(){ + println!("{:?}", song); + } }