Add additional explain

This commit is contained in:
lone 2025-06-03 22:25:40 +08:00
parent cb60c8887c
commit a7aa8e3d10

View File

@ -10,6 +10,14 @@
use std::fmt::Display;
// Make the struct generic over `T`.
//
// Note: We could also add the Display trait bound here at the struct level, i.e.,
// `struct ReportCard<T: Display> { ... }`. That would enforce that every `ReportCard` instance
// must have a grade that is displayable. However, by not placing the bound here, we allow
// the creation of `ReportCard` instances with non-displayable grades (but then we cannot use the `print` method).
// Since the main purpose of this struct is to be printable, it would also be reasonable to add the bound at the struct level.
// In this solution, we choose to put the bound only in the `impl` block to show that we can conditionally
// implement methods only when the type satisfies certain traits. This offers more flexibility in some advanced scenarios.
struct ReportCard<T> {
// ^^^
grade: T,
@ -19,6 +27,10 @@ struct ReportCard<T> {
}
// To be able to print the grade, it has to implement the `Display` trait.
//
// Note: We implement the `print` method only for `ReportCard<T>` where `T` implements `Display`.
// This means that if we have a `ReportCard` with a grade that doesn't implement `Display`,
// we can still create the instance, but we cannot call the `print` method on it.
impl<T: Display> ReportCard<T> {
// ^^^^^^^ require that `T` implements `Display`.
fn print(&self) -> String {