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.
- Rust doesn't allow moving part of a structure out, but there are better ways than just
- 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
- Use the CodeLLDB extension in VS Code
- For vim, https://alpha2phi.medium.com/setting-up-neovim-for-rust-debugging-termdebug-and-vimspector-df749e1ba47c walks through the process of setting up CodeLLDB with the Vimspector plugin.
- In unit tests use
cargo test -- --nocapture
to show anything the tests write to stdout
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.