-
Notifications
You must be signed in to change notification settings - Fork 0
Home
Daniel Cortes edited this page Nov 4, 2024
·
1 revision
So, what is going on here?
#[derive(Debug)]
enum Media {
Book { title: String, author: String },
Movie { title: String, director: String },
Audiobook { title: String },
}
Here is a trick for understanding what is kind of going on behind the scenes:
So right above main
if we had defined structs we would have to define some functions that look like:
fn print_book(book: Book) {}
fn print_movie(movie: Movie) {}
And that would be tedious, so we can actually do the following with an enum:
#[derive(Debug)]
enum Media {
Book { title: String, author: String },
Movie { title: String, director: String },
Audiobook { title: String },
}
fn print_media(media: Media) {
println!("{:#?}", media);
}
fn main() {
let audiobook = Media::Audiobook {
title: String::from("An Audiobook"),
};
print_media(audiobook);
}
I will head to my terminal and run this:
Audiobook {
title: "An Audiobook",
}
We can also make a book or movie and use the exact same print_media
function.
So we can make one single structure that defines several types of data that are similar but distinctly different.
Once we have done so we can define other functions or vectors or structs that make use of this structure. So we get a good amount of code reuse with it.