From 4321471cc25f14d08e3ba4fe4e0edb313ebe695a Mon Sep 17 00:00:00 2001 From: My Chiffon Nguyen Date: Sat, 22 Jun 2024 15:34:57 +0200 Subject: [PATCH] Quiz 3: add Grade trait, and related methods; add trait bound syntax to ReportCard struct; group into modules; --- exercises/quiz3.rs | 73 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 61 insertions(+), 12 deletions(-) diff --git a/exercises/quiz3.rs b/exercises/quiz3.rs index 3b01d313..d19f5f92 100644 --- a/exercises/quiz3.rs +++ b/exercises/quiz3.rs @@ -16,24 +16,74 @@ // // Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE +/// 'grade' module contains the Grade trait, which converts a grade to a string +mod grade { + /// Trait to convert a grade (f32 or &str) to a string + pub trait Grade { + /// Method to convert a grade to a string + fn grade(&self) -> String; + } + + impl Grade for f32 { + /// Method to convert a numeric grade to an alphabetic grade + fn grade(&self) -> String { + if *self >= 4.5 { + "A+".to_string() + } else if *self >= 4.0 { + "A".to_string() + } else if *self >= 3.5 { + "B+".to_string() + } else if *self >= 3.0 { + "B".to_string() + } else if *self >= 2.5 { + "C+".to_string() + } else if *self >= 2.0 { + "C".to_string() + } else if *self >= 1.5 { + "D+".to_string() + } else if *self >= 1.0 { + "D".to_string() + } else { + "F-".to_string() + } + } + } -pub struct ReportCard { - pub grade: f32, - pub student_name: String, - pub student_age: u8, + impl Grade for &str { + fn grade(&self) -> String { + self.to_string() + } + } } -impl ReportCard { - pub fn print(&self) -> String { - format!("{} ({}) - achieved a grade of {}", - &self.student_name, &self.student_age, &self.grade) +/// 'report_card' module contains the ReportCard struct, which prints the report card with the student's name, age, and grade +mod report_card { + use super::grade::Grade; + use std::fmt::Display; + + /// Change grade to a generic type T that implements the Grade trait + pub struct ReportCard { + pub grade: T, + pub student_name: String, + pub student_age: u8, + } + + // Add trait bound syntax to the impl block to allow the use of the Grade trait, and Display (for self.grade) + impl ReportCard { + /// Print the report card, showing the student's name, age, and grade + pub fn print(&self) -> String { + format!( + "{} ({}) - achieved a grade of {}", + &self.student_name, &self.student_age, &self.grade + ) + } } } #[cfg(test)] mod tests { - use super::*; + use super::grade::Grade; + use super::report_card::ReportCard; #[test] fn generate_numeric_report_card() { @@ -50,9 +100,8 @@ mod tests { #[test] fn generate_alphabetic_report_card() { - // TODO: Make sure to change the grade here after you finish the exercise. let report_card = ReportCard { - grade: 2.1, + grade: "A+", student_name: "Gary Plotter".to_string(), student_age: 11, };