18 Oct 2025
How to write good rust code
Results vs Options
- Use options where there is no context to be given. A failure in an external command, for example, is not an Option. There's almost always context behind the failure.
- Don't try to be fault tolerant, especially when you have a lot of possible input space and not a lot of output space. It is bound to fail. Fail hard and fail fast. Similar response also goes for running external commands and parsing their output.
- Parse, don't validate.
- Use anyhow to propagate error message contexts.
- Make sure that any error message is good enough to be propagated upwards as is, unless it's
supposed to be a generic function that just fails on failure. Examples include supac's
run_commandandrun_command_for_stdoutfunctions. These preferably need more specific contexts on what's happening.- The above is true usually when the function is being exported for regular use and does something where the arguments are the principal focus for the side effect being done.
- Prefer using
Errover logging. Only prefer logging if there's scope of recovery/possibility of a default value to be used. Use debug logging for things in gen. - Fail hard and fail fast, even for optional parsing. What's ill-configured is ill-configured.
- ANYHOW CAN BE USED AS MAIN'S RETURN TYPE!!!
Function declaration order
- BFS style. Based on earliest usage.
