Skip to content

Comment on Perhaps Rust Needs "Defer"

Comments

One popular implementation of "defer" in Rust is the scopeguard crate [0]. Behind the scenes, all it does is create an object that will run your function once it's dropped (usually when it falls out of scope). It can be more robust than manually sprinkling library-specific free()s everywhere for FFI, since the function will also be run during an unwinding panic, sort of like a "finally" block. I've certainly found it helpful for one-off uses of certain APIs that I can't be bothered to write a bunch of Drop boilerplate for.

[0] https://docs.rs/scopeguard/latest/scopeguard/

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.