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.
Your Task
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:
- Define a trait
Describablewith a single methoddescribethat returns aString. - Implement this trait for the struct
Person. - Implement this trait for the struct
Book.
Requirements
- The
Personstruct should have fieldsname: Stringandage: u8. - The
Bookstruct should have fieldstitle: Stringandauthor: String. - The
describemethod forPersonshould return a string like"Person: Alice, Age: 30". - The
describemethod forBookshould return a string like"Book: Rust Programming, Author: Jane Doe".
Hints
If you're stuck, here are some hints to help you solve the challenge:
<details> <summary>Click here to reveal hints</summary>- Implement a trait for a struct using
impl TraitName for StructName. e.g.impl Describable for Person {fn describe(&self) -> String {format!("Person: {}, Age: {}", self.name, self.age)}} - Don't forget to use the
&selfas the parameter for thedescribemethod in the trait.
pub trait Describable {fn describe(&self) -> String;}pub struct Person {pub name: String,pub age: u8,}pub struct Book {pub title: String,pub author: String,}// TODO: Implement the `Describable` trait for `Person` and `Book`// Example usagepub fn main() {let person = Person {name: "Alice".to_string(),age: 30,};let book = Book {title: "Rust Programming".to_string(),author: "Jane Doe".to_string(),};println!("{}", person.describe());println!("{}", book.describe());}