I'm using the decorator pattern and find that while it works on a mutable reference, it doesn't work on an immutable one. Does anyone have a better idea?
pub struct Slave {
pub is_drive: bool
}
impl Slave {
fn is_drive(&self) -> bool {
self.is_drive
}
}
Drive
is a decorator type of 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
can only be used with a &mut Slave
, but I'd like to get a &Drive
from a &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);
}
Edit:
Drive
can only be used with a &mut Slave
, but sometimes I need it for a &Slave
. I don't use accessor functions because Slave should not depend on 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
}
}
...
}