Rust Opinions
Rust Style Guidelines#
cargo fmt
is your friend. I use the default settings.clippy
is a great tool, and should be a requirement for getting PRs merged.unsafe
is fine when called for, but use carefully- It should be commented
- It should be wrapped in a safe abstraction
Error Handling#
- Panicking always indicates a bug
- Especially in a library
- Also in an application
- Doesn’t mean you can’t call
panic
- But if that code path is actually activated, it’s a bug
- Use
?
even in toy projects unwrap
does not belong in your repos.expect
is acceptable.- It is too prone to abuse.
clippy
should be configured to ban it. - Use
expect
whereunwrap
would be appropriateexpect
is appropriate for indicating logic errors- A panic is always a bug, especially in a library
unlock()
is an appropriate place to useexpect
expect
is not appropriate as a band-aid on bad flow control- Use
if let Some(x) =
rather thanis_some
followed byunwrap
- Use
?
should be preferred in most non-logic error situations- Or explicit handling
- Write a useful message with
expect
- To aid debugging if you were wrong
- To show to the reader why you think it will never be called
- Consider writing panicking functions over calling
expect
repeatedly- Array indexes are a good example of this
- This is controversial
- Some experts think
unwrap
is OK in some situations where I allowexpect
- I think
unwrap
is too tempting for the situations where neitherexpect
orunwrap
is OK
- I think
- No experts think
unwrap
is fine to use much more liberally than that
- Some experts think
unwrap
is OK in draft code where it is interpreted as aXXX
- Don’t let this into your production codebase
- Make sure you have the
unwrap
check inclippy
enabled in CI so it doesn’t slip in
- It is too prone to abuse.
- Use
thiserror
for libraries, useanyhow
oreyre
for binaries.
Things I love about Rust#
The Programming Language Itself#
- That it has proper sum types in
enum
s - That it has all the expressive power of C++ if you need it, while demarcating a safe subset
- That Rust lifetimes have finally rescued “regions” from academia
- And therefore made RAII complete
- That it doesn’t have OOP-style inheritance
Standard Library#
- The
map
APIs are quite excellent
The Ecosystem#
- That everyone uses
log
but there are multiple backends available - That
cargo
is so ergonomic
How I wish Rust had been made differently (but it’s too late to change)#
- I wish
unwrap
were not part of the standard library - I wish the C/C++ distinction between
.
and->
were retained, because I think sometimes automatically dereferencing and sometimes not is surprising.
Newsletter
Find out via e-mail when I make new posts!