Rust Cheatsheet

Written — Updated
  • Asynchronous Rust
    • Asynchronous Closures
      • You can define code blocks as async, just like you can with functions. You'll usually need to use move on the code block as well.
      • the_function(|| move async {
          // the code
    • Taking Asynchronous Closure Arguments
      • It starts like usual, with an Fn, FnOnce, or FnMut trait boundary, but you have to define the return type and you can't do impl Future in the trait.
      • The way around this is to define another type parameter, and put the trait boundary on that.
        async fn takes_an_async_closure<F, Fut, R, E>(f : F) -> impl Future
            F: FnOnce() -> Fut,
            Fut: Future<Output = Result<R, E>>,
            R: Send,
            E: Send
  • Inner Arc Pattern
    • For types that you want to always be clonable and within an Arc without needing to deal with the Arc everywhere, you can make an outer NewType that just contains an Arc<InnerType>.
    • In this case you do have to implement Clone manually for things to really work properly. But it's pretty easy.
    • struct Queue(Arc<QueueInner>);
      impl Clone for Queue {
          fn clone(&self) -> Queue {
      // Implement methods on the outer type, which access the inner type.
      impl Queue {
        fn do_job(&self) {
          // do stuff with self.0 here...
    • This pattern should only be used for types that you know will be passed around between threads or async contexts, such as connection pools. Otherwise it's usually better to let the user of your library add an Arc if needed.
  • Partial Moves
    • Rust doesn't allow moving part of a structure out, but there are better ways than just clone.
    • Use mem::replace to take items out from structures without needing to take ownership of the entire thing.
    • Destructuring also helps when you want to eventually move all the items out of the structure.
      • Lately I've been just destructuring more and more.
  • Serde
    • To enable auto-derive of Serialize and Deserialize traits, the best way is to enable the derive feature in the serde crate. You can also just include the serde-derive crate manually.
  • Performance
    • fxhash crate is good for fast hashing that doesn't need to be cryptographically secure.
    • Rust Performance Book
    • Enable Link-time Optimization
      • [profile.release]
        lto = true

Thanks for reading! If you have any questions or comments, please send me a note on Twitter. And if you enjoyed this, I also have a newsletter where I send out interesting things I read and the occasional nature photo.

You can check out a recent issue, or enter your email below to subscribe.