|
|
|
|
|
by verdagon
1510 days ago
|
|
To clarify, I was talking about making RAII, not using RAII. And it surprised me too, when I learned that the borrow checker rejects it. To see it in action: Have a Database object, and try to have multiple Transaction objects that might commit something to it, in their drop(). It's unfortunately not possible, because they can't all have a &mut Database as struct fields. We can sacrifice speed (by using Cell's copying or Rc's counting) or safety (by using unsafe). Most RAII we see uses unsafe FFI under the hood, which is why it was so surprising to me. |
|
However, achieving something like what you want is still more than possible in Rust. You can do this with the pattern of 'interior mutability', which in its simplest form is just a Mutex. This allows upgrading a shared reference to an exclusive reference, so that you can safely mutate an object while upholding the expectations that a mutable reference is exclusive, and a non-mutable reference does not change from under your feet.
Of course, for a database, you will probably want a more advanced implementation of interior mutability, so that you can commit multiple transactions at the same time. (Or not, it seems to work quite well for SQLite.)