DEV Community

Discussion on: My first impressions of Rust

louy2 profile image
Yufan Lou • Edited

Thank you for sharing your experience of trying out Rust!

For optional struct fields, there's derive-new which gives you various T::new() constructors. Derive is borrowed from Haskell, similar to Project Lombok for Java.

The three Fn* traits are a consequence of Rust's memory safety model built on linear logic, commonly known as lifetime / ownership. They are still first class values, meaning you can use let to bind them with a name and pass them in parameters like any other. They are just more complicated than function in JavaScript or closure in Java.

Rust has Fn, FnMut and FnOnce in order to enforce at compile time rules which Java or JavaScript can only panic at run time:

  • FnOnce can only run once. These can be functions like free() in C or close() in Closable. Calling FnOnce twice on the same object or context would not compile. thread::spawn() uses FnOnce to enforce that no references are passed to the new thread.
  • FnMut can mutate its captured state. This is most similar to a normal function in Java and JavaScript. There can be only one FnMut capturing the same binding existing at one time. If more, it would not compile.
  • Fn cannot mutate its captured state. This is somewhat analogous to const function in C++.

There's an order: FnOnce < FnMut < Fn. A Fn* can be used in the place of ones to its left.

deepu105 profile image
Deepu K Sasidharan

Wow. Thanks this is so far the most simple and straightforward explanation I got and now it makes more sense. I guess I would have to update the post to reflect what I learned about functions.