quiz3.rs (1813B)
1 // An imaginary magical school has a new report card generation system written 2 // in Rust! Currently, the system only supports creating report cards where the 3 // student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the 4 // school also issues alphabetical grades (A+ -> F-) and needs to be able to 5 // print both types of report card! 6 // 7 // Make the necessary code changes in the struct `ReportCard` and the impl 8 // block to support alphabetical report cards in addition to numerical ones. 9 10 use std::fmt::Display; 11 12 // Make the struct generic over `T`. 13 struct ReportCard<T> { 14 // ^^^ 15 grade: T, 16 // ^ 17 student_name: String, 18 student_age: u8, 19 } 20 21 // To be able to print the grade, it has to implement the `Display` trait. 22 impl<T: Display> ReportCard<T> { 23 // ^^^^^^^ require that `T` implements `Display`. 24 fn print(&self) -> String { 25 format!( 26 "{} ({}) - achieved a grade of {}", 27 &self.student_name, &self.student_age, &self.grade, 28 ) 29 } 30 } 31 32 fn main() { 33 // You can optionally experiment here. 34 } 35 36 #[cfg(test)] 37 mod tests { 38 use super::*; 39 40 #[test] 41 fn generate_numeric_report_card() { 42 let report_card = ReportCard { 43 grade: 2.1, 44 student_name: "Tom Wriggle".to_string(), 45 student_age: 12, 46 }; 47 assert_eq!( 48 report_card.print(), 49 "Tom Wriggle (12) - achieved a grade of 2.1", 50 ); 51 } 52 53 #[test] 54 fn generate_alphabetic_report_card() { 55 let report_card = ReportCard { 56 grade: "A+", 57 student_name: "Gary Plotter".to_string(), 58 student_age: 11, 59 }; 60 assert_eq!( 61 report_card.print(), 62 "Gary Plotter (11) - achieved a grade of A+", 63 ); 64 } 65 }