Going through rustlings for the first time
at main 83 lines 2.2 kB view raw
1#[derive(Debug)] 2struct Package { 3 sender_country: String, 4 recipient_country: String, 5 weight_in_grams: u32, 6} 7 8impl Package { 9 fn new(sender_country: String, recipient_country: String, weight_in_grams: u32) -> Self { 10 if weight_in_grams < 10 { 11 // This isn't how you should handle errors in Rust, but we will 12 // learn about error handling later. 13 panic!("Can't ship a package with weight below 10 grams"); 14 } 15 16 Self { 17 sender_country, 18 recipient_country, 19 weight_in_grams, 20 } 21 } 22 23 fn is_international(&self) -> bool { 24 // ^^^^^^^ added 25 self.sender_country != self.recipient_country 26 } 27 28 fn get_fees(&self, cents_per_gram: u32) -> u32 { 29 // ^^^^^^ added 30 self.weight_in_grams * cents_per_gram 31 } 32} 33 34fn main() { 35 // You can optionally experiment here. 36} 37 38#[cfg(test)] 39mod tests { 40 use super::*; 41 42 #[test] 43 #[should_panic] 44 fn fail_creating_weightless_package() { 45 let sender_country = String::from("Spain"); 46 let recipient_country = String::from("Austria"); 47 48 Package::new(sender_country, recipient_country, 5); 49 } 50 51 #[test] 52 fn create_international_package() { 53 let sender_country = String::from("Spain"); 54 let recipient_country = String::from("Russia"); 55 56 let package = Package::new(sender_country, recipient_country, 1200); 57 58 assert!(package.is_international()); 59 } 60 61 #[test] 62 fn create_local_package() { 63 let sender_country = String::from("Canada"); 64 let recipient_country = sender_country.clone(); 65 66 let package = Package::new(sender_country, recipient_country, 1200); 67 68 assert!(!package.is_international()); 69 } 70 71 #[test] 72 fn calculate_transport_fees() { 73 let sender_country = String::from("Spain"); 74 let recipient_country = String::from("Spain"); 75 76 let cents_per_gram = 3; 77 78 let package = Package::new(sender_country, recipient_country, 1500); 79 80 assert_eq!(package.get_fees(cents_per_gram), 4500); 81 assert_eq!(package.get_fees(cents_per_gram * 2), 9000); 82 } 83}