How to write easy to refactor Rust
Note: this section is still under development, who knows if it’ll exist in the future
Tags: #rust , #easy-to-refactor
Ideas
- Type inference is your friend
- Try and write types for something once. The more you write types for something the more you’d have to change it.
- Use Self for the return type of constructors with
..Default::default()
- Associated types can be used so you don’t have to keep writing the type
- Rust supports
-> impl Something
, you don’t have to write out the concrete type every time - Try and implement as many built in traits or traits as possible
- Don’t be afraid to implement your trait for built in types
- Use Self for the return type of constructors with
- Instead of casting all the time, let the compiler infer the cast
- Try and write types for something once. The more you write types for something the more you’d have to change it.
impl
blocks make things really hard, try creating traits to abstract away all that pain- Traits allow you to define the relationship between different types that you’re using, plus adding a little bit of logic. There is a limit to their power though (doesn’t work when you want to construct a particular struct)
- infer types more
- only works for stack allocated variables (not params)
- use free generic variables when you don’t care
- Know when to use generic parameters or associated types
- Write more functional code
- FP is the best at composable / refactorable code
- This is also useful when writing tests, you know the core pillars that it’s built on are working fine, so it’s easier to adapt the tests
- Avoid having to refactor at all
- Pass on the benefits
- You should be writing APIs that help people write code that’s easy to refactor. This means implementing Default or Vector methods, if you can work with iterating over a value you should implement iter / from iter methods.
- Find crates that could possibly make use of your library and implement traits for them. These could be hidden behind a feature flag.
- Generics generate more code so be careful
- Macros for repretetive tasks
- mdbook get and insert macro
- This case is an example of using a macro to allow
try_into
and into to work properly
- This case is an example of using a macro to allow
- Quick tip: use the paste libray to make code generation even better
- Rule of thumb: if you have to write something multiple times why not write it once with a macro?
- mdbook get and insert macro
- If all else fails, learn some Vim-fu