+3
-3
exercises/quizzes/quiz3.rs
+3
-3
exercises/quizzes/quiz3.rs
···
12
12
// block to support alphabetical report cards in addition to numerical ones.
13
13
14
14
// TODO: Adjust the struct as described above.
15
-
struct ReportCard {
16
-
grade: f32,
15
+
struct ReportCard<T> {
16
+
grade: T,
17
17
student_name: String,
18
18
student_age: u8,
19
19
}
20
20
21
21
// TODO: Adjust the impl block as described above.
22
-
impl ReportCard {
22
+
impl<T: std::fmt::Display> ReportCard<T> {
23
23
fn print(&self) -> String {
24
24
format!(
25
25
"{} ({}) - achieved a grade of {}",
+63
-2
solutions/quizzes/quiz3.rs
+63
-2
solutions/quizzes/quiz3.rs
···
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
+
1
32
fn main() {
2
-
// DON'T EDIT THIS SOLUTION FILE!
3
-
// It will be automatically filled after you finish the exercise.
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
+
}
4
65
}