In Rust, supertraits allow you to define a trait hierarchy where a derived trait requires another trait to be implemented first. This is useful when modeling interfaces that build upon or depend on other capabilities.
In this challenge, you will define two traits: Person and Student. The Person trait provides the ability to retrieve a name, while the Student trait extends Person by adding additional fields specific to students, such as an ID and a field of study.
Your Task
-
Define a trait
Person:- It should require a method
fn name(&self) -> Stringthat returns the name of the person.
- It should require a method
-
Define a trait
Studentthat is a supertrait ofPerson:- It should require methods:
fn id(&self) -> u32to return the student ID.fn field_of_study(&self) -> Stringto return the student's field of study.
- It should require methods:
-
Implement both traits for a struct
Undergraduate:- The
Undergraduatestruct should have fieldsid,name, andfield_of_study. - Use the
Studenttrait to provide the student's ID, name, and field of study.
- The
Hints
If you're stuck, here are some hints to help you solve the challenge:
<details> <summary>Click here to reveal hints</summary>- Use the syntax
trait Student: Person {}to defineStudentas a supertrait ofPerson. - Remember to implement both
PersonandStudentfor theUndergraduatestruct. - Use
self.name.clone()andself.field_of_study.clone()to returnStringvalues without ownership issues. - You can call methods from the supertrait explicitly using
<YourType as YourTrait>::method_name().
// 1. Finish the trait definitionpub trait Person// 2. Finish the trait definitionpub trait Student// 3. Finish the struct definitionpub struct Undergraduate {// Define fields for id, name, and field_of_study here...}// 4. Implement the necessary traits for the Undergraduate struct// Example usagepub fn main() {let student = Undergraduate {id: 101,name: "John Doe".to_string(),field_of_study: "Computer Science".to_string(),};assert_eq!(student.name(), "John Doe");assert_eq!(student.id(), 101);assert_eq!(student.field_of_study(), "Computer Science");}