Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to be explicit with type annotation?

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?

like image 656
treiff Avatar asked Aug 02 '17 12:08

treiff


1 Answers

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.

like image 97
Shepmaster Avatar answered Nov 01 '22 18:11

Shepmaster