Rust Variable Bindings

Rust variable bindings are straightforward, but a bit different than in some other popular languages. An initial declaration / binding begins with the let keyword, and can assume an appropriate type based on the initial value:

This sets up the variable x as a signed 32-bit integer of type i32. If you need to specify a particular type, that can optionally follow the variable name

This gets us an unsigned 8-bit integer variable.

By default, Rust variables are immutable. This might seem like a frustrating choice at first, but the logic behind it includes the notion that it would be easier for the compiler to prevent you from altering a value you did not intend to change if you had to be explicit about wanting a value mutable in the first place. [Sounds good for safety-rich programming domains such as avionics!]

To purposefully make a variable mutable, include the mut modifier:

Another fine design choice for safety-conscious programmers is that Rust requires variables to have initial values. Granted, compilers for some other popular languages issue warnings when variables are left uninitialized, but deeming an uninitialized variable to be a compilation error should strongly encourage more intentional variable declaration behavior.

Rust variable bindings are block-scoped, such that

will not work, because y goes out of scope at the end of the block it is enclosed within.

Rust variable bindings also support shadowing, which is useful to introduce a new variable within a block with the same name as one outside the block, but which can seem a bit confusing when used to effectively sneak around the immutability rules:

What we have here are actually two variables named x. The first one is not destroyed or overwritten by the second one, but due to scoping and shadowing rules, the first one is now no longer accessible.

More: read the Variable Bindings chapter in The Rust Programming Language.

Leave a Reply

Your email address will not be published. Required fields are marked *