Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -main.rs---------------------------------------------------------------------------
- fn test_device(device: &mut dyn Device) {
- println!("Tests with basic remote.");
- let mut basic_remote = BasicRemote::new(device);
- basic_remote.power();
- device.print_status();
- println!("Tests with advanced remote.");
- let mut advanced_remote = AdvancedRemote::new(device);
- advanced_remote.basic_remote().power();
- advanced_remote.mute(); // -> error[E0499]: cannot borrow `advanced_remote` as mutable more than once at a time
- }
- fn main() {
- test_device(&mut Tv::default());
- }
- -advanced_remote.rs------------------------------------------------------------------
- pub struct AdvancedRemote<'a> {
- basic_remote: BasicRemote<'a>,
- }
- impl<'a> AdvancedRemote<'a> {
- pub fn new(device: &'a mut dyn Device) -> Self {
- Self {
- basic_remote: BasicRemote::new(device),
- }
- }
- pub fn basic_remote(&mut self) -> &'a mut BasicRemote {
- &mut self.basic_remote
- }
- pub fn mute(&mut self) {
- println!("Remote: mute");
- self.basic_remote.device().set_volume(0);
- }
- }
- -basic_remote.rs--------------------------------------------------------------------
- pub struct BasicRemote<'a> {
- device: &'a mut dyn Device,
- }
- impl<'a> BasicRemote<'a> {
- pub fn new(device: &'a mut dyn Device) -> Self {
- Self { device }
- }
- pub fn device(&mut self) -> &mut dyn Device {
- self.device
- }
- }
- impl<'a> Remote for BasicRemote<'a> {
- fn power(&mut self) {
- println!("Remote: power toggle");
- if self.device.is_enabled() {
- self.device.disable()
- } else {
- self.device.enable()
- }
- }
- fn volume_down(&mut self) {
- println!("Remote: volume down");
- self.device.set_volume(self.device.volume() - 10);
- }
- fn volume_up(&mut self) {
- println!("Remote: volume up");
- self.device.set_volume(self.device.volume() + 10);
- }
- fn channel_down(&mut self) {
- println!("Remote: channel down");
- self.device.set_channel(self.device.channel() - 1);
- }
- fn channel_up(&mut self) {
- println!("Remote: channel up");
- self.device.set_channel(self.device.channel() + 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement