My favorite rust function

My favorite rust function is std::mem::drop which is used to free or deallocate a value, similar to free() in C.

Quoting the docs from stdlib, This function is not magic; it is literally defined as

pub fn drop<T>(_x: T) { }

How could a function definition with an empty body ever be useful?

Ownership and lifetimes are Rust’s most unique features and it gives you the predictability and performance of static memory management without any of its safety problems.

The ownership rules are pretty simple.

  1. Each value in Rust has a variable that’s called its owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value will be dropped.

Calling a function moves the ownership of the arguments and if the called function decides to do nothing with it, the arguments will be dropped - which is exactly what we wanted!

Now this might seem like a hack, but it really is not. Most languages would either ask the programmers to explicitly call free() or implicitly call a magic runtime.deallocate() within a complex garbage collector.

The beauty of programming language design is not building the most complex edifice like Scala or making the language unacceptably restricted like Go - but giving the programmer the ability to represent complex ideas elegantly and safely. Rust really shines in that regard.

A language that doesn’t affect the way you think about programming is not worth knowing. ― Alan J. Perlis


This post was edited after publishing, see the full history on github.