by vmchale · 6y ago · 0 comments
With linear types you can guarantee that a destructor is run, so you can create objects with lifetimes that are not only bounded from below, but bounded by above. There are some common patterns in e.g. C libraries that rely on this--for example, you might register a callback on an object, and you want to assert that the object's lifetime is shorter than the callback's (so the callback is never called outside its lifetime).
Since Rust doesn't have linear types, you have to use unsafe{}.
This can be accomplished by a method that consumes the object and returns the closure (which now owns the object), and a closure method's that borrows the object back from it.
That doesn't actually guarantee that the closure will outlive the object. You would need linear types in order to do that, and Rust does not have linear types.
In the particular API I'm working with, you pass the closure in to an object when you create it, and you have to make sure that the closure outlives the object. The only way to do that within the Rust type system is by making the closure 'static, which is... less than ideal. So you use unsafe{} instead.
This is because any object may outlive its specified lifetime. Lifetimes are only lower bounds. So if I have lifetimes 'b and 'a, and 'b : 'a, this only means that the LIFETIME 'b must be at least as long as the LIFETIME 'a, but any particular object with lifetime 'b may live arbitrarily long, as long as it lasts at least as long as 'b. And any object which is 'a may last arbitrarily long, but at least as long as 'a.
As in, you wouldn't write the code this way if you didn't have to. You do get memory safety in return... but you can see where the desire for a more eloquent approach might arise.