Skip to content

Add additional explain for quiz3 solution #2253

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions solutions/quizzes/quiz3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand Down
Loading