Finished implementing code with iterator

This commit is contained in:
Dawid Pietrykowski 2023-06-20 18:39:02 +02:00
parent 23d31053b1
commit f8281d894b

View File

@ -1,3 +1,75 @@
fn main() { #[allow(dead_code)]
println!("Hello, world!"); #[derive(Debug)]
struct Song {
name: String,
artist: String,
duration: f32
}
struct Playlist{
songs: Vec<Song>,
}
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<Self::Item> {
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);
}
} }