RAII for failure-prone initializations?

⚓ Rust    📅 2026-02-24    👤 surdeus    👁️ 3      

surdeus

Design question: I'm working on a library to control hardware devices using a serial protocol.

The natural way to design such drivers is, of course, resource acquisition is initialization.

However, the problem is that initializing the structs that represent these devices is quite complex; it's necessary to initial a serial connection, then send several messages in the device's format and wait for appropriate responses. The devices themselves are not always reliable.

I have some cleanup code that runs in Drop; for the most part, the same code should run if initialization fails partway through, but, of course, the struct itself is not yet available at this point.

Is RAII still the best way to implement this? Are there good examples of ways to modify the code so that I can share cleanup code between failures that occur in init and ordinary Drops?

3 posts - 3 participants

Read full topic

🏷️ Rust_feed