1. 1
    Type Inference in Rust
    1m 58s

Type Inference in Rust

InstructorPascal Precht

Share this video with your friends

Send Tweet

This lesson explains Type Inference in Rust and how it allows the compiler to figure out by itself, what type variables have when they get their values assigned.

There are cases when the compiler cannot infer a value's type through static analysis. In such cases, developers have to provide type annotations explicitly.

J. Matthew
~ 4 years ago

I'm curious what is the best practice (if there is one) regarding whether or not to annotate the type explicitly when it's not required by the compiler. I write a lot of TypeScript, and my preference is always to annotate the type even when it could be inferred, for the sake of instant clarity and readability. Take this example:

const isTrueOrFalse: boolean = false;

Here there are multiple indicators of the nature of the variable: 1) The "is" prefix on the name, which conventionally denotes a boolean; 2) The explicit type declaration after the name; 3) The initial value of false. However, it could also be written const myVar = false (or even var myVar = false), and despite the removal of two of those indicators, both the compiler and someone reading the code could easily infer it is a boolean by the initial value. Still, I like including the other indicators, because you don't have to read past the equals sign to understand the variable, and the explicit declaration feels "safer" to me as well (whether it actually is or not, I'm not sure).

I'm sure the answer could vary between languages, but is there a general consensus among Rust developers?

Pascal Prechtinstructor
~ 4 years ago

Good question:

I'm curious what is the best practice (if there is one) regarding whether or not to annotate the type explicitly when it's not required by the compiler. I write a lot of TypeScript, and my preference is always to annotate the type even when it could be inferred

So also here, this really depends on your style and probably the conventions you follow alone or with your team. I personally like to look at it this way: If something can be expressed in less characters, it should be expressed in less characters (unless readability suffers from it).

Given the example you just brought up, doing:

const isTrueOrFalse: boolean = false;

Doesn't really add any additional value.

Generally, I think it's good to try to get away with as little annotation as you can and once the compiler complains that it can't infer something, you help out where it's needed.

I'm sure the answer could vary between languages, but is there a general consensus among Rust developers?

I can't really provide an answer that is backed by actual research, but I would assume that most of Rust developers also omit annotations where they aren't necessary (that's what type inference is for after all).

Hope this makes sense!