0

I'm trying to create a struct that owns an object, but also owns other objects that have references to the first object.

pub struct IbbIo<'a, I2C: Write + WriteRead> {
    bus : BusManagerSimple<I2C>,
    bargraph : Bargraph<I2cProxy<'a, NullMutex<I2C>>>,
}

impl<I2C, E> IbbIo<'_, I2C>
    where I2C: WriteRead<Error = E>  + Write<Error = E>,
{
    pub fn new(i2c: I2C) -> Self {
        let bus = BusManagerSimple::new(i2c);
        let bargraph = Bargraph::new(bus.acquire_i2c(), 0x70, None);
        IbbIo {
            bus,
            bargraph,
        }
    }
}

I get an error:

cannot move out of bus because it is borrowed bus.acquire_i2c() is where the borrow occurs

I understand the borrow checker is observing that in creating the Bargraph I've borrowed bus, and then I'm trying to move it into the struct IbbIo but I'm also trying to move bargraph too.

I guess i could do something like make bargraph be an Option and only initialize bus to create the object and then borrow from bus to create bargraph later, but I'd like to know if it's possible to create the struct moving bus into it even though bargraph has reference since both are going to be members of the same struct and have the same lifetime ultimately?

piojo
  • 5,701
  • 1
  • 21
  • 32

0 Answers0