samedi 27 juin 2020

How do I mutably use an instance from multiple instances on the stack in Rust?

I am relatively new to Rust, coming from mainly C++ and Python trying to learn how to do things the rust way. The following code uses unsafe code to be able to use an instance of A mutably from instances of both B and C. I don't think I should need to use unsafe code to do this, but I could be wrong. Is there a better way without using dynamically allocated memory, and without flattening B and C into the same implementation?

use core::cell::UnsafeCell;

struct A {}

impl A {
    fn do_something(&mut self) {
        // does something
    }
}

struct B<'a> {
    a: &'a UnsafeCell<A>,
}

impl<'a> B<'a> {
    fn do_something_with_a(&mut self) {
        unsafe { (*self.a.get()).do_something() }
    }
}

struct C<'a> {
    a: &'a UnsafeCell<A>,
    b1: B<'a>,
    b2: B<'a>,
}

impl<'a> C<'a> {
    fn new(a: &'a UnsafeCell<A>) -> Self {
        Self {
            a: a,
            b1: B{a: a},
            b2: B{a: a},
        }
    }

    fn use_b(&mut self) {
        self.b1.do_something_with_a();
        self.b2.do_something_with_a();
    }

    fn use_a(&mut self) {
        unsafe { (*self.a.get()).do_something() }
    }
}

fn main() {
    let a = UnsafeCell::new(A{});
    let mut c = C::new(&a);
    c.use_b();
    c.use_a();
}

Aucun commentaire:

Enregistrer un commentaire