Skip to content

Commit

Permalink
Quiz 3: add Grade trait, and related methods; add trait bound syntax …
Browse files Browse the repository at this point in the history
…to ReportCard struct; group into modules;
  • Loading branch information
chiffonng committed Jun 22, 2024
1 parent e4d2c30 commit 4321471
Showing 1 changed file with 61 additions and 12 deletions.
73 changes: 61 additions & 12 deletions exercises/quiz3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T: Grade> {
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<T: Grade + Display> ReportCard<T> {
/// 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() {
Expand All @@ -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,
};
Expand Down

0 comments on commit 4321471

Please sign in to comment.