I've been reading through The Rust Programming Language, but I've been unable to find a clear answer on what the best practice is for type annotation, specifically with primitive types.
For example, letting the compiler determine the type:
let v = true;
Or, using explicit type annotation:
let v: bool = true;
In general I like to be explicit, but I am unsure if this is against best practices or the preferred style. Would compile times be improved due to the compiler not having to infer the type?
against best practices or the preferred style
Yes, I'd say that the prevailing style is to let type inference happen as much as possible.
Would compile times be improved due to the compiler not having to infer the type?
Technically, yes, there should be some small savings, but in the vast majority of cases it wouldn't be measurable. The compiler already has to figure out what types everything is to make sure the code type checks.
There are some pathological cases where there's exponential time consumed, but that can often be "fixed" with a single well-placed type when it's needed.
In general I like to be explicit
Then you do what you need to do. Often, when learning, we are more explicit than we need to be. Once you become familiar with the language, you'll drop the training wheels. Just be prepared for a lot of asides when experienced Rust programmers look at your code ("you know, you don't have to put this type here...").
I prefer to be less explicit in types because I feel the rest of the program (variable and function names, mainly) should represent the logic. It doesn't matter in most cases if I have a BTreeMap
or a HashMap
, but the concept of a key-value structure is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With