Solve last struct and generics

This commit is contained in:
Enrico Bozzolini 2020-08-21 22:05:16 +02:00
parent 86f728acd2
commit 8039ced662
4 changed files with 14 additions and 19 deletions

View File

@ -1,10 +1,8 @@
// 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");
}

View File

@ -1,13 +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 }
}
}

View File

@ -7,17 +7,16 @@
// Make the necessary code changes to support alphabetical report cards, thereby making
// the second test pass.
// I AM NOT DONE
pub struct ReportCard {
pub grade: f32,
pub struct ReportCard<T> {
pub grade: T,
pub student_name: String,
pub student_age: u8,
}
impl ReportCard {
impl<T: ToString> ReportCard<T> {
pub fn print(&self) -> String {
format!("{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade)
&self.student_name, &self.student_age, &self.grade.to_string())
}
}
@ -37,9 +36,8 @@ mod tests {
#[test]
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,
};

View File

@ -22,12 +22,12 @@ impl Package {
fn is_international(&self) -> bool {
// Something goes here...
self.from != self.to
self.recipient_country != self.sender_country
}
fn get_fees(&self, cents_per_kg: i32) -> i32 {
// Something goes here... (beware of grams to kg conversion)
self.weight * cost_per_kg
(self.weight_in_grams * cents_per_kg) / 100
}
}
@ -59,7 +59,7 @@ mod tests {
let sender_country = String::from("Spain");
let recipient_country = String::from("Spain");
let cents_per_kg = 8.0;
let cents_per_kg = 300;
let package = Package::new(sender_country, recipient_country, 1500);