Resource Cleanup

2 Posts

Drop in Depth

6 minute

Earlier we used Drop as the first replacement for C cleanup paths: when a value leaves scope, its resource is released automatically.

That already replaces many goto cleanup patterns. But when writing library code that wraps file handles, connections, locks, temporary directories, or FFI handles, “scope exit releases the value” is not enough.

C programmers still need answers to practical questions:

  • What is the exact cleanup order?
  • How do you release early?
  • What if cleanup can fail?
  • Which struct field is dropped first?
  • Can Drop move a field out?
  • How should an FFI handle be wrapped?

These are the parts of Drop that matter in real engineering code.

Read More

Resource Cleanup: From cleanup to Drop

5 minute

In C, resource cleanup is maintained by people.

Open a file and you need fclose. Allocate memory and you need free. Take a lock and you need to unlock it. Initialize an object and every error path must destroy it. Once a function has several resources, goto cleanup becomes the common structure.

Rust does not remove cleanup. It binds cleanup responsibility to whoever owns the resource. When a value leaves scope, its cleanup logic runs automatically. This mechanism is Drop.

Read More