How do I implement an external trait for an external struct?

Your problem is that serializing the Connection object tries to turn a live database connection — with lots of internal state, pointers, locks, open file handles — into a flat bunch of dumb bytes that do nothing, and then Rust would probably close the actual connection for you (because the serialized copy doesn't keep ownership of the original). So you'd be left with a xeroxed copy of what used to be an internal state of a database connection, and no db connection.

What you need to do is to keep the Connection object on the Rust side and never send it to the Erlang side. The only thing Erlang needs to know is which connection object it's talking about, and the "which" question can be answered with a raw pointer value, which you can get from a Box or Arc or similar. It'll be just a 64-bit number, which is trivial to serialize and won't destroy the connection. You could also have a global array of Rust connections and send an integer to Erlang that is an index in that array (but that's just an example, in practice sending pointers is easier to manage).

3 Likes