From 1cf7c1885717c234c2459a424f2252f052372878 Mon Sep 17 00:00:00 2001 From: Emre AYDIN <aeaydin1@gmail.com> Date: Wed, 6 Jan 2021 15:07:44 +0300 Subject: [PATCH] Generics exercises complete --- exercises/generics/generics1.rs | 4 +--- exercises/generics/generics2.rs | 10 ++++------ exercises/generics/generics3.rs | 16 +++++++++------- 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/exercises/generics/generics1.rs b/exercises/generics/generics1.rs index 967287e..07a3ed8 100644 --- a/exercises/generics/generics1.rs +++ b/exercises/generics/generics1.rs @@ -1,9 +1,7 @@ // This shopping list program isn't compiling! // Use your knowledge of generics to fix it. -// I AM NOT DONE - fn main() { - let mut shopping_list: Vec<?> = Vec::new(); + let mut shopping_list: Vec<&str> = Vec::new(); shopping_list.push("milk"); } diff --git a/exercises/generics/generics2.rs b/exercises/generics/generics2.rs index 0cb59ad..57ae948 100644 --- a/exercises/generics/generics2.rs +++ b/exercises/generics/generics2.rs @@ -1,14 +1,12 @@ // This powerful wrapper provides the ability to store a positive integer value. // Rewrite it using generics so that it supports wrapping ANY type. -// I AM NOT DONE - -struct Wrapper { - value: u32, +struct Wrapper<T> { + value: T, } -impl Wrapper { - pub fn new(value: u32) -> Self { +impl<T> Wrapper<T> { + pub fn new(value: T) -> Self { Wrapper { value } } } diff --git a/exercises/generics/generics3.rs b/exercises/generics/generics3.rs index 64dd9bc..39c58e9 100644 --- a/exercises/generics/generics3.rs +++ b/exercises/generics/generics3.rs @@ -10,18 +10,20 @@ // Execute 'rustlings hint generics3' for hints! -// I AM NOT DONE +use std::fmt; -pub struct ReportCard { - pub grade: f32, +pub struct ReportCard<T: fmt::Display> { + pub grade: T, pub student_name: String, pub student_age: u8, } -impl ReportCard { +impl<T: fmt::Display> ReportCard<T> { pub fn print(&self) -> String { - format!("{} ({}) - achieved a grade of {}", - &self.student_name, &self.student_age, &self.grade) + format!( + "{} ({}) - achieved a grade of {}", + &self.student_name, &self.student_age, &self.grade + ) } } @@ -46,7 +48,7 @@ mod tests { fn generate_alphabetic_report_card() { // TODO: Make sure to change the grade here after you finish the exercise. let report_card = ReportCard { - grade: 2.1, + grade: "A+", student_name: "Gary Plotter".to_string(), student_age: 11, };