Rust best practices

来自WHY42

Variables

Prefer let bindings over mutable variables

Let bindings are immutable by default, meaning that once a value is assigned to them, it cannot be changed. This helps prevent bugs and errors in the code because there’s no risk of accidentally changing the value of a variable without realizing it. It also makes the code easier to read and understand since you know exactly what values are being used at any given time.

Mutable variables, on the other hand, can be changed after they have been declared. While this may seem like an advantage, it can lead to unexpected behavior if not handled properly. For example, if a mutable variable is passed as an argument to a function, its value could be changed within the function without the caller knowing about it. This can cause confusion and make debugging difficult.

Using let bindings instead of mutable variables also encourages better coding practices. Since let bindings are immutable, developers must think more carefully about how their code will work before writing it. This leads to cleaner, more organized code that is easier to maintain over time.

Furthermore, Rust provides several features that make working with let bindings even easier. The match expression allows for pattern matching on let bindings, making it easy to handle different cases. There are also destructuring assignments which allow multiple let bindings to be declared at once. Finally, Rust has a powerful type system which ensures that all let bindings are correctly typed and initialized.[1]