mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-01 16:29:18 +00:00
Restriction by trait Grade so that the ReportCard has and ONLY has two types: numeric and alphabetic.
This commit is contained in:
parent
e852e60416
commit
1444cb9737
@ -9,9 +9,21 @@
|
|||||||
|
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
// Make the struct generic over `T`.
|
// Grade Trait
|
||||||
struct ReportCard<T> {
|
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<T: Grade> {
|
||||||
|
// ^^^^^^^^^^
|
||||||
grade: T,
|
grade: T,
|
||||||
// ^
|
// ^
|
||||||
student_name: String,
|
student_name: String,
|
||||||
@ -19,8 +31,8 @@ struct ReportCard<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// To be able to print the grade, it has to implement the `Display` trait.
|
// To be able to print the grade, it has to implement the `Display` trait.
|
||||||
impl<T: Display> ReportCard<T> {
|
impl<T: Display + Grade> ReportCard<T> {
|
||||||
// ^^^^^^^ require that `T` implements `Display`.
|
// ^^^^^^^^^^^^^^^ require that `T` implements `Display` and `Grade`.
|
||||||
fn print(&self) -> String {
|
fn print(&self) -> String {
|
||||||
format!(
|
format!(
|
||||||
"{} ({}) - achieved a grade of {}",
|
"{} ({}) - achieved a grade of {}",
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user