我使用装饰器模式并发现虽然它适用于可变引用,但它并不适用于不可变引用模式。有没有人有更好的主意?
pub struct Slave {
pub is_drive: bool
}
impl Slave {
fn is_drive(&self) -> bool {
self.is_drive
}
}
Drive
是Slave
的装饰器类型。
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
}
}
...
}
答案 0 :(得分:0)
以std::cell::Ref
和std::cell::RefMut
为例,我将为Drive
提供&Slave
,为DriveMut
提供&mut Slave
。