summaryrefslogtreecommitdiff
path: root/rustlings/solutions/07_structs/structs3.rs
diff options
context:
space:
mode:
authorHunter Kvalevog <hunter@kvog.sh>2026-09-19 17:44:02 -0500
committerHunter Kvalevog <hunter@kvog.sh>2026-09-19 17:44:02 -0500
commit13c7b05a26b78cb63bed5d2afdf8eb927197286e (patch)
tree29ae22718398ef3c1d605ea8725ebbac9c8b4ac3 /rustlings/solutions/07_structs/structs3.rs
parent4791a7ab0400713568f8c9594d9ac2bac10cd8ae (diff)
rustlings: complete 07
Diffstat (limited to 'rustlings/solutions/07_structs/structs3.rs')
-rw-r--r--rustlings/solutions/07_structs/structs3.rs83
1 files changed, 81 insertions, 2 deletions
diff --git a/rustlings/solutions/07_structs/structs3.rs b/rustlings/solutions/07_structs/structs3.rs
index dcf2377..3f878cc 100644
--- a/rustlings/solutions/07_structs/structs3.rs
+++ b/rustlings/solutions/07_structs/structs3.rs
@@ -1,4 +1,83 @@
+#[derive(Debug)]
+struct Package {
+ sender_country: String,
+ recipient_country: String,
+ weight_in_grams: u32,
+}
+
+impl Package {
+ fn new(sender_country: String, recipient_country: String, weight_in_grams: u32) -> Self {
+ if weight_in_grams < 10 {
+ // This isn't how you should handle errors in Rust, but we will
+ // learn about error handling later.
+ panic!("Can't ship a package with weight below 10 grams");
+ }
+
+ Self {
+ sender_country,
+ recipient_country,
+ weight_in_grams,
+ }
+ }
+
+ fn is_international(&self) -> bool {
+ // ^^^^^^^ added
+ self.sender_country != self.recipient_country
+ }
+
+ fn get_fees(&self, cents_per_gram: u32) -> u32 {
+ // ^^^^^^ added
+ self.weight_in_grams * cents_per_gram
+ }
+}
+
fn main() {
- // DON'T EDIT THIS SOLUTION FILE!
- // It will be automatically filled after you finish the exercise.
+ // You can optionally experiment here.
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ #[should_panic]
+ fn fail_creating_weightless_package() {
+ let sender_country = String::from("Spain");
+ let recipient_country = String::from("Austria");
+
+ Package::new(sender_country, recipient_country, 5);
+ }
+
+ #[test]
+ fn create_international_package() {
+ let sender_country = String::from("Spain");
+ let recipient_country = String::from("Russia");
+
+ let package = Package::new(sender_country, recipient_country, 1200);
+
+ assert!(package.is_international());
+ }
+
+ #[test]
+ fn create_local_package() {
+ let sender_country = String::from("Canada");
+ let recipient_country = sender_country.clone();
+
+ let package = Package::new(sender_country, recipient_country, 1200);
+
+ assert!(!package.is_international());
+ }
+
+ #[test]
+ fn calculate_transport_fees() {
+ let sender_country = String::from("Spain");
+ let recipient_country = String::from("Spain");
+
+ let cents_per_gram = 3;
+
+ let package = Package::new(sender_country, recipient_country, 1500);
+
+ assert_eq!(package.get_fees(cents_per_gram), 4500);
+ assert_eq!(package.get_fees(cents_per_gram * 2), 9000);
+ }
}