logoalt Hacker News

solaticyesterday at 6:57 AM1 replyview on HN

Rust's problem is similar to Go's - the language makes some very strong guarantees, and FFI breaks those guarantees, so trying to work with FFI in those languages "infects" the codebase and breaks the value-add of working with the codebase to begin with.

In Rust's case, it's the necessity of wrapping FFI with unsafe. Memory deallocation e.g. cudaFree() is just part of the underlying reality; trying to handle memory management in a language with a borrow checker rather defeats the purpose of using a language with a borrow checker in the first place. Python lets library authors write __enter__ and __exit__ dunder methods to ensure that memory deallocation is handled correctly via Python context managers, which is a much more elegant abstraction. Yes, in Rust you can implement the Drop trait, but then the caller needs to remember to put the object in its own block... like I said, it's definitely possible with Rust, it's just not as nice of a story.


Replies

gspryesterday at 3:10 PM

I don't see how what you describe doesn't in general apply to FFI between any languages with different resource management philosophies. In particular:

> Yes, in Rust you can implement the Drop trait, but then the caller needs to remember to put the object in its own block...

Why would you need to remember to put the object in its own block? If you want to manually control deallocation, just call drop manually (or put the object in its own block if you really prefer). If you don't care, just let the Rust compiler pick a time to drop. In both cases, the most important guarantee – that drop doesn't happen while references to the object live – is still upheld.