From fc147836543ef43b3344b36e64ba3a0753f53c88 Mon Sep 17 00:00:00 2001 From: Michele Sessa Date: Wed, 16 Nov 2022 17:26:13 +0000 Subject: [PATCH] feat(car_rental): add new exercise for rust exams --- subjects/car_rental/README.md | 89 +++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 subjects/car_rental/README.md diff --git a/subjects/car_rental/README.md b/subjects/car_rental/README.md new file mode 100644 index 000000000..b386f8b41 --- /dev/null +++ b/subjects/car_rental/README.md @@ -0,0 +1,89 @@ +## car_rental + +### Instructions + +Create a struct named `Car` and another one named `RentalBusiness`. + +The scope of the exercise will be to modify and operate on the `Car` in the `RentalBusiness` even if this element is not declared as mutable. + +### Expected Functions and Structures + +```rust +use std::cell::Ref; +use std::cell::RefCell; +use std::cell::RefMut; + +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Car { + pub color: String, + pub plate: String, +} + +#[derive(Debug)] +pub struct RentalBusiness { + pub car: RefCell, +} + +impl RentalBusiness { + pub fn rent_car(&self) -> Ref {} + pub fn sell_car(&self) -> Car {} + pub fn repair_car(&self) -> RefMut {} + pub fn change_car(&self, new_car: Car) {} +} +``` + +### Usage + +Here is a program to test your function: + +```rust +use car_rental::*; +use std::cell::RefCell; + +fn main() { + let car_rental = RentalBusiness { + car: RefCell::new(Car { + color: "red".to_string(), + plate: "AAA".to_string(), + }), + }; + + println!("{:?}", car_rental.rent_car()); + println!("{:?}", car_rental.repair_car()); + + { + let mut car = car_rental.repair_car(); + car.color = "blue".to_string(); + } + + println!("{:?}", car_rental.rent_car()); + + car_rental.change_car(Car { + color: "pink".to_string(), + plate: "WWW".to_string(), + }); + + println!("{:?}", car_rental.rent_car()); + + println!("{:?}", car_rental.sell_car()); + println!("{:?}", car_rental.sell_car()); +} +``` + +And its output: + +```console +$ cargo run +Car { color: "red", plate: "AAA" } +Car { color: "red", plate: "AAA" } +Car { color: "blue", plate: "AAA" } +Car { color: "pink", plate: "WWW" } +Car { color: "pink", plate: "WWW" } +Car { color: "", plate: "" } +$ +``` + +### Notions + +- [std::cell::RefCell](https://doc.rust-lang.org/std/cell/struct.RefCell.html) +- [Struct std::rc::Rc](https://doc.rust-lang.org/std/rc/struct.Rc.html)