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
where unwrap
would be appropriate
expect
is appropriate for indicating logic errors
- A panic is always a bug, especially in a library
unlock()
is an appropriate place to use expect
expect
is not appropriate as a band-aid on bad flow control
- Use
if let Some(x) =
rather than is_some
followed by unwrap
?
should be preferred in most non-logic error situations
- 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 allow expect
- I think
unwrap
is too tempting for the situations where neither expect
or unwrap
is OK
- No experts think
unwrap
is fine to use much more liberally than that
unwrap
is OK in draft code where it is interpreted as a XXX
- Don’t let this into your production codebase
- Make sure you have the
unwrap
check in clippy
enabled in CI so it doesn’t slip in
- Use
thiserror
for libraries,
use anyhow
or eyre
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
- That it doesn’t have OOP-style inheritance
Standard Library#
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.
comments powered by