>> Let's use Visual Studio Code to see how traits work in action.
I'll begin by creating a new project called
traits and opening it up in Visual Studio Code.
Inside our main file,
let's create a struct called Film.
A film has a title,
a director, and a studio.
Now let's create a another struct called Book.
A book has a title,
an author, and a publisher.
Both films and books come in catalogs.
So let's create a Catalog trait to contain behavior related to
catalogs that can be used on both films and books.
No matter what thing is being cataloged,
we need a way to describe it.
Let's add a described method to our catalog trait.
Now let's implement the Catalog trait for the Film struct.
When we call describe on a Film,
it will print out a line that says that the title was directed
by the director name through the studio.
In our main function,
let's go ahead and create an instance of the Film struct.
Let's call it Captain Marvel,
and it's a film where the title is Captain Marvel.
The directors are Anna Boden and Ryan Fleck,
and the studio is Marvel Studios.
Now let's call the describe method on Captain Marvel.
When I run this code,
I see that Captain Marvel was directed by
Anna Boden and Ryan Fleck through Marvel Studios.
Now let's implement the Catalog trait for the Book struct.
In this case, when I call describe on a Book,
it will print out the title was written by the author
and published by the publisher defined for that book.
Back in my main function,
let's create an instance of the Book struct and call it Elantris.
The title is Elantris.
The author is Brandon Sanderson and the publisher is Tor Books.
Now let's call describe on Elantris.
When I run this code,
I see Elantris was written by
Brandon Sanderson and published by Tor Books.
There are a lot of
different types of things that can be in a catalog,
all of which might have different behavior when you describe them.
Let's go ahead and create
some default behavior for
the describe function in the Catalog trait.
In this case, when a struct has catalog implemented on it,
but does not have its own behavior for the describe method,
we will print out, we need
more information about this type of media.
Now, let's create a new struct called the Album struct.
Album has a title,
an artists, and a label,
and let's go ahead and implement the Catalog trait for album,
but notice that we do not define behavior for the describe method.
We choose to use the default behavior for now, at least.
Back in my main function.
Let's go ahead and create an album called let_it_be,
and the title is Let it Be,
the artist is the Beatles,
and the label is Apple.
Then let's call the describe method on our let_it_be album.
Let's run this code.
I see that we need more information about this type of media.
That is our demo of traits.
They can be confusing at first,
especially if you're used to object-oriented programming,
but as you use them more,
you see how useful and how powerful they are. Happy coding.
[MUSIC]