From 1444cb973754d20e9fcb601685c535196986148e Mon Sep 17 00:00:00 2001 From: 1vk3y Date: Mon, 7 Oct 2024 13:17:40 +0800 Subject: [PATCH] Restriction by trait `Grade` so that the `ReportCard` has and ONLY has two types: numeric and alphabetic. --- solutions/quizzes/quiz3.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/solutions/quizzes/quiz3.rs b/solutions/quizzes/quiz3.rs index 7b912782..4ffe71ec 100644 --- a/solutions/quizzes/quiz3.rs +++ b/solutions/quizzes/quiz3.rs @@ -9,9 +9,21 @@ use std::fmt::Display; -// Make the struct generic over `T`. -struct ReportCard { - // ^^^ +// Grade Trait +trait Grade {} +//^^^^^^^^^^^^ + +// Implements the trait for `f32` (numeric, e.g. 1.0 -> 5.5) +impl Grade for f32 {} +//^^^^^^^^^^^^^^^^^^^ + +// Implements the trait for `str` (alphabetic, A+ -> F-) +impl Grade for &str {} +//^^^^^^^^^^^^^^^^^^^^ + +// Make the struct generic over `T: Grade`. +struct ReportCard { + // ^^^^^^^^^^ grade: T, // ^ student_name: String, @@ -19,8 +31,8 @@ struct ReportCard { } // To be able to print the grade, it has to implement the `Display` trait. -impl ReportCard { - // ^^^^^^^ require that `T` implements `Display`. +impl ReportCard { + // ^^^^^^^^^^^^^^^ require that `T` implements `Display` and `Grade`. fn print(&self) -> String { format!( "{} ({}) - achieved a grade of {}",