Ownership

1

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