装饰器模式和不可变引用

时间:2017-07-30 08:28:26

标签: rust decorator

我使用装饰器模式并发现虽然它适用于可变引用,但它并不适用于不可变引用模式。有没有人有更好的主意?

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。我不使用访问器功能,因为Slave不应该依赖于Drive:

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
       }
    }
    ...
}

1 个答案:

答案 0 :(得分:0)

std::cell::Refstd::cell::RefMut为例,我将为Drive提供&Slave,为DriveMut提供&mut Slave

相关问题