mirror of
https://github.com/rust-lang/rustlings.git
synced 2025-12-28 06:49:19 +00:00
Add additional explain
This commit is contained in:
parent
cb60c8887c
commit
a7aa8e3d10
@ -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 {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user