finish generics exercises

This commit is contained in:
lukaszKielar 2020-06-30 20:35:12 +02:00
parent 5a9d6a6677
commit fbc00d495e
3 changed files with 33 additions and 29 deletions

View File

@ -1,10 +1,7 @@
// This shopping list program isn't compiling! // This shopping list program isn't compiling!
// Use your knowledge of generics to fix it. // Use your knowledge of generics to fix it.
// I AM NOT DONE
fn main() { fn main() {
let mut shopping_list: Vec<?> = Vec::new(); let mut shopping_list: Vec<&str> = Vec::new();
shopping_list.push("milk"); shopping_list.push("milk");
} }

View File

@ -1,13 +1,12 @@
// This powerful wrapper provides the ability to store a positive integer value. // This powerful wrapper provides the ability to store a positive integer value.
// Rewrite it using generics so that it supports wrapping ANY type. // Rewrite it using generics so that it supports wrapping ANY type.
// I AM NOT DONE struct Wrapper<T> {
struct Wrapper { value: T,
value: u32
} }
impl Wrapper { impl<T> Wrapper<T> {
pub fn new(value: u32) -> Self { pub fn new(value: T) -> Self {
Wrapper { value } Wrapper { value }
} }
} }

View File

@ -6,18 +6,20 @@
// Make the necessary code changes to support alphabetical report cards, thereby making // Make the necessary code changes to support alphabetical report cards, thereby making
// the second test pass. // the second test pass.
use std::fmt::{Debug, Display};
// I AM NOT DONE pub struct ReportCard<T> {
pub struct ReportCard { pub grade: T,
pub grade: f32,
pub student_name: String, pub student_name: String,
pub student_age: u8, pub student_age: u8,
} }
impl ReportCard { impl<T: Display + Debug> ReportCard<T> {
pub fn print(&self) -> String { pub fn print(&self) -> String {
format!("{} ({}) - achieved a grade of {}", format!(
&self.student_name, &self.student_age, &self.grade) "{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade
)
} }
} }
@ -32,17 +34,23 @@ mod tests {
student_name: "Tom Wriggle".to_string(), student_name: "Tom Wriggle".to_string(),
student_age: 12, student_age: 12,
}; };
assert_eq!(report_card.print(), "Tom Wriggle (12) - achieved a grade of 2.1"); assert_eq!(
report_card.print(),
"Tom Wriggle (12) - achieved a grade of 2.1"
);
} }
#[test] #[test]
fn generate_alphabetic_report_card() { fn generate_alphabetic_report_card() {
// TODO: Make sure to change the grade here after you finish the exercise. // TODO: Make sure to change the grade here after you finish the exercise.
let report_card = ReportCard { let report_card = ReportCard {
grade: 2.1, grade: "A+".to_string(),
student_name: "Gary Plotter".to_string(), student_name: "Gary Plotter".to_string(),
student_age: 11, student_age: 11,
}; };
assert_eq!(report_card.print(), "Gary Plotter (11) - achieved a grade of A+"); assert_eq!(
report_card.print(),
"Gary Plotter (11) - achieved a grade of A+"
);
} }
} }