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