Perhaps Rust needs "defer"

submited by
Style Pass
2024-11-06 09:00:05

In a previous article I mentioned that we use the defer idiom in Rust through a crate, but that it actually rarely gets past the borrow checker. Some comments were claiming this issue does not exist surprised and I did not have an example at hand.

Well, today at work I hit this issue again so I thought I would document it. And the whole experience showcases well how working in Rust with lots of FFI interop feels like.

It allocates and returns an dynamically allocated array as a pointer and a length. Of course in reality, Foo has many fields and the values are not known in advance but what happens is that we send messages to a Smartcard to ask it to send us a piece of data residing on it, and it replies with some encoded messages that our library decodes and returns to the user.

If we feel fancy (and non-portable), we can even automate the freeing of the memory in C with __attribute(cleanup), like defer (ominous sounds). But let's not, today. Let's focus on the Rust side.

Leave a Comment
Related Posts