Rust Cheatsheet

Written — Updated
  • https://github.com/rust-unofficial/patterns has a lot of patterns
  • Error Handling
    • anyhow is great for just merging random errors together when you don't really care otherwise and just want to get the error message out and all the various errors to have the same type. (i.e. most CLI utilities)
    • thiserror is nice for structured error types where you want to add extra formatting or otherwise handle errors in a more detailed way.
      • Can wrap an anyhow inside a thiserror as well
      • #[derive(Error, Debug)]
        pub enum RequestError {
          #[error("Invalid query string: {0}")]
          QueryStringError(#[from] serde_qs::Error),
        
          #[error(transparent)]
          Other(#[from] anyhow::Error),
        }
  • 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.
  • 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
  • Debugging

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.