Rust Tutorial – Part 2 – Variables

Rust, Tutorials / Sunday, December 3rd, 2017

[This post is part of the series on Rust programming tutorials that I’m writing for enjoyment. All the tutorial links are here.]

Variables . . . things that hold other things. What other things? These other things vary from language to language, and range from values to references to direct memory addresses (the last one being very, very scary, and is the reason I did no system programming so far but have now picked up Rust).

Variables, as the term implies, are supposed to vary, or change over the course of the program. So without wasting any more time, let’s try out variables in Rust:

fn main() {
    let x = 32;  
    println!("The value of x is {}", x);

And when you run it:

The value of x is 32

Well, no surprises there! You’ll notice that the curly braces{} are used to substitute variable values in a string we’re about to print. That’s how Rust knows where to fit what when the final output is shown.

Now let’s try some more simple stuff:

fn main() {
    let x = 32;
    x += 23;
    println!("The value of x is {}", x);

And when you compile it, you get:

error[E0384]: re-assignment of immutable variable `x`
2 |     let x = 32;
  |         - first assignment to `x`
3 |     x += 23;
  |     ^^^^^^^ re-assignment of immutable variable

error: aborting due to previous error

Uh, oh. An error? Surely we’ve hit upon a bug in the compiler? What could be more simple than adding an integer value to a variable that already contains an integer?

Well, while this sounds conceptually valid, for Rust, not all variables are created equal. Some can change over the course of time, and some cannot. By default variables can’t be changed once they’ve been set; if you want them to change, you need to explicitly tell the compiler so:

fn main() {
    let mut x = 32;
    x += 23;
    println!("The value of x is {}", x);

Notice the keyword mut here. It tells Rust that this variable isΒ mutable. In other words, we intend its value to change over time. And if you compile and run this program now:

The value of x is 55

All fine and dandy!

But we’ve left out any important point: why, in the name of God, can variables not be changed in Rust by default?

Well, I’m afraid the complete explanation is really, really long, but I’ll try to do my best.

Basically, when the world started programming, the popular languages in the world were those that followed the Object Oriented approach to modeling solutions. Entities in our programs were thought of as representing something independent and concrete, and a large body of theory was developed to “simplify” the process. Languages like C (though not object-oriented), C++ and Java became incredibly popular, which was followed by JavaScript, PHP, Python, Ruby, and so forth.

After so many years of programming like this, people started to feel that they were spending too much time pulling their hair trying to track changes made to their variables. When something is accessible by a lot of things and can be changed, it’s not pretty. And so began a gradual shift to another style of programming called Functional Programming, where everything is a function and there is not much theory to digest. Functional Programming style insists on immutability – things cannot be changed. You only send something to a function, which works on it and returns a new, transformed value, and then you use that new value. The argument is that this approach is simpler to program, track and teach, and results in fewer bugs. The surging popularity of languages like Clojure, Scala (though not purely functional), Elixir, Haskell, F#, etc., seems to indicate that (hey, Rust is also functional! πŸ™‚ ).

There seems to be a homecoming of sorts in the programming world, as people are re-discovering the joys of one of the oldest forms of programmingΒ (warning: very heavy read).

So, to avoid confusion and keep bugs to a minimum, Rust won’t allow you to change a variable’s value by default.

Speaking of immutability, the Erlang language (on which WhatsApp’s inital backend was built) doesn’t allow you toΒ ever change a variable value, and its proponents say it’s the best thing they saw in their lives.

Man, that got long despite my best efforts. 😐

But I hope it was of some help and interest.

The next part of this tutorial is here.

2 Replies to “Rust Tutorial – Part 2 – Variables”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.