Type Inference in Rust

Pascal Precht
InstructorPascal Precht
Share this video with your friends

Social Share Links

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.

Instructor: [00:00] The Rust compiler comes with a feature called type inference. What that means is that it's able to figure out the type of our values without us explicitly annotating things like variables.

[00:11] For example, here we see a variable condition with the value false of type Boolean. We have a variable some_number with the value 5 of type i32. There's another one which is a string slice reference, and we have an array of string slices. All of these variables annotate explicitly their type.

[00:33] We can run this program and we'll see that the compiler is able to compile without any issues. However, even if we go ahead and remove these annotations for most of these variables, we'll see that the compiler is still able to figure out their types.

[00:54] Sometimes however, the compiler is not able to infer the type. This is, for example, the case for APIs like Parse, which lets us parse a string slice to a string. It also allows us to parse the string slice to a number.

[01:13] Since Rust can't know by itself to which type we want to parse to, providing no type annotation at all in this case will cause a compile error. The compiler tells us that we should consider giving the number variable a type.

[01:29] In this particular case, there's two ways to go about this. We can either provide the annotation right after the variable name as we did before. Another way is to use the so-called turbofish syntax, which requires us to put two colons here, followed by an angle bracket, followed by the type, followed by closing angle bracket. Saving this file and running this code, we see that the compiler is happy.