2017-07-30 22 views
0

我使用裝飾模式,發現雖然它在可變引用上工作,但它不能在不可變引用上工作。有沒有人有更好的主意?裝飾模式和不可變的引用

pub struct Slave { 
    pub is_drive: bool 
} 

impl Slave { 
    fn is_drive(&self) -> bool { 
     self.is_drive 
    } 
} 

DriveSlave一個裝飾類型。

pub struct Drive<'a> { 
    pub slave: &'a mut Slave, 
} 

impl<'a> Drive<'a> { 
    // Create drive. 
    pub fn new(slave: &mut Slave) -> Drive { 
     Drive { 
      slave: slave, 
     } 
    } 
} 

Drive只能用&mut Slave使用,但我想獲得一個&Drive&Slave

fn main() { 
    let s1 = &mut Slave { is_drive: true }; 
    let d1 = Drive::new(s1); 

    // Doesn't work 
    // let s2 = & Slave { is_drive: true }; 
    // let d2 = Drive::new(s2); 
} 

編輯:

Drive只能用&mut Slave使用,但有時我需要它&Slave

fn config_slave(slave: &mut Slave) { 
    ... 
    if slave.is_drive() { 
     let drive = Drive::new(slave) { 
      // call functions provided by Drive 
     } 
    } 
    ... 
} 

fn print_slave(slave: &Slave) { 
    ... 
    if slave.is_drive() { 
     let drive = Drive::new(slave) { 
      // Call functions provided by Drive 
     } 
    } 
    ... 
} 
+0

你爲什麼要定義'pub slave:&'一個mut Slave,'可變嗎?把它改成'pub slave:&'Slave,'。否則,是的,這可能是重複的。 – Shepmaster

+3

標準庫例如:'std :: cell :: Ref'和'std :: cell :: RefMut'。如果標準庫作者沒有設法使用單一類型來處理可變和不可變的訪問(在編譯時),那麼很可能你不會......並且如果你確實管理它,那麼請解釋你確實幫助完善了標準庫! –

回答

0

std::cell::Refstd::cell::RefMut爲例,我將提供一個&SlaveDrive&mut Slave一個DriveMut:因爲奴隸不應該依賴於驅動器,我不使用存取功能。