In Rust, traits define shared behavior that types can implement. A trait acts as a contract, requiring implementing types to provide certain methods. This makes traits one of the most powerful features for achieving polymorphism and code reusability in Rust.
For example, the Display
trait allows custom formatting for types using the {}
formatter. Similarly, you can define your own traits to describe behaviors relevant to your program.
In this challenge, you'll implement a trait Describable
and use it to define a common interface for objects that can provide a description. Your task is to:
Describable
with a single method describe
that returns a String
.Person
.Book
.Person
struct should have fields name: String
and age: u8
.Book
struct should have fields title: String
and author: String
.describe
method for Person
should return a string like "Person: Alice, Age: 30"
.describe
method for Book
should return a string like "Book: Rust Programming, Author: Jane Doe"
.If you're stuck, here are some hints to help you solve the challenge:
impl TraitName for StructName
. e.g.
&self
as the parameter for the describe
method in the trait.