Playback speed
×
Share post
Share post at current time
0:00
/
0:00
Transcript

Types and Shadowing

Strange Behaviour of Rust Variables

Continuing my gobsmacked marvelling at Rust, I’ve discovered a couple of interesting things which I thought we should cover before looking at tuples.

Types and Variable Declaration

Rust is strongly-typed so we can’t take a variable of one type and set it to another type.

We cannot do this:

and then immediately do this:

The type of x is fixed at f64, a 64-bit floating-point number, when you declare it. You cannot then assign an integer literal to it.

However, what surprised me was, you can do this:

Evidently by redeclaring x, we are declaring a completely different variable, which can have a different type.

Shadowing

The second variable now shadows the first variable. The nature of shadowing becomes clearer in the following program.

This produces the following output:

We output the value of the first variable called x. Then, within a restricted scope, we created a new x variable and output the value of that. When this second x goes out of scope, we print the value of x again, and since only the first variable is now in scope, that’s the value we get.

I also discovered Rust was created by someone called Graydon Hoare, who created it as a side-project of some sort when he was 29 years old. I must look into this more.

Discussion about this podcast

John Purcell
John Purcell
Authors
John Purcell