Rust for JavaScript Devs 2: Variables

Brian Heise
5 min readFeb 17, 2022

Learn how to declare mutable and immutable variables

Photo by Max Duzij on Unsplash

This is Part 2 in the series Rust for JavaScript devs, where we explore writing Rust code from a JavaScript developer’s perspective. The goal is to give JavaScript developers the foundational knowledge they need to contribute to Rust projects in the JavaScript ecosystem.

Last time we learned how to write a hello world app in Rust and compared that to how we would do it in JavaScript; today we’re going to look at assigning variables and incorporating their outputs into text written to the console.

The complete code for this exercise can be found here.

Introducing Today’s Program

Our target program, written in JavaScript, is as follows:

// JavaScript
const myName = "Tom";
let myAge = 39;
console.log("Hello world!");
console.log(`My name is ${myName}`);
console.log(`I am ${myAge} years old`);
myAge += 1;console.log(`Next year I'll be ${myAge} years old`);

The console output is here:

Console output from the program

Here we introduce 2 variables: myName and myAge. We use the const keyword with my name since we don’t want to update this value. However, we use let with myAge because we do want to update that value later on.

It’s a rather trivial program to be sure, but good enough to give us an idea of the 2 most common types of variables in Rust and how to use them. Beware, JavaScript devs: Rust shares many keywords with JavaScript, but their usage is very different!

Immutable Variables

In our JavaScript program we didn’t want the value of our myName variable to change so we used the keyword const to define it. To achieve the same purpose in Rust, somewhat confusingly for us JS developers, we’ll use let. That’s right — the way to make an immutable variable in Rust looks the same as how we would write a mutable variable in JS. Let’s look at the code (note the inclusion of the mandatory main function).

// Rust
fn main() {
let my_name = "Tom";
println!("Hello world!");
}

Notice also that we used snake_case rather than camelCase for the variable name — this is a Rust convention.

To prove to yourself that the variable is indeed immutable, try running the following code and see what happens:

// Rust
fn main() {
let my_name = "Tom";
my_name = "Edward";
println!("Hello world!");
}

You’ll see a couple warnings about unused variables but skip past those to the error message:

// shell
cargo run
[...]error[E0384]: cannot assign twice to immutable variable `my_name`
--> src/main.rs:3:5
|
2 | let my_name = "Tom";
| -------
| |
| first assignment to `my_name`
| help: consider making this binding mutable: `mut my_name`
3 | my_name = "Edward";
| ^^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
For more information about this error, try `rustc --explain E0384`.

We find that we indeed cannot mutate it, just like our JavaScript version. You’ll notice that it does give us a suggestion about how to make it mutable if that’s what we wanted: help: consider making this binding mutable: `mut my_name`. In the next section we’ll take a look at this mut keyword.

Mutable Variables

In Rust, to achieve the same purpose as you would with the let keyword we use let mut. Let’s see how it works with our failing example from above:

// Rust
fn main() {
let mut my_name = "Tom";
my_name = "Edward";
println!("Hello world!");
}

This now compiles and successfully prints “Hello World!”. Let’s apply what we just learned to create a mutable Rust version of let myAge = 39 and myAge += 1.

// Rust
fn main() {
let my_name = "Tom";
let mut my_age = 39;
println!("Hello world!"); my_age += 1;
}

Run cargo run and you’ll find that this compiles and runs.

String Interpolation

Ok! So we can assign our variables, but how do we get them printed to the console as part of a message, as we did in the JavaScript code:

// JavaScript
console.log(`My name is ${myName}`);
console.log(`I am ${myAge} years old`);

As we’ll see, Rust has a rather different approach to this. The equivalent Rust is as shown below:

// Rust
// Note: main function removed for brevity
println!("My name is {}", my_name);
println!("I am {} years old", my_age);

As we can see, in Rust we need to leave a placeholder, “{}”, in the output string and then pass in the value as a parameter to the println! macro.

Note that you aren’t limited to a single parameter per string — you can use as many as you want:

// Rust  println!("My name is {} and I am {} years old", my_name, my_age);

There are all kinds of interesting variations on println! so if you want to learn more about it, take a look at this article.

The Final Rust Program

Let’s look at both programs side-by-side. First, JavaScript:

// JavaScript
const myName = "Tom";
let myAge = 39;
console.log("Hello world!");
console.log(`My name is ${myName}`);
console.log(`I am ${myAge} years old`);
myAge += 1;console.log(`Next year I'll be ${myAge} years old`);

Now the Rust:

// Rust
fn main() {
let my_name = "Tom";
let mut my_age = 39;
println!("Hello world!");
println!("My name is {}", my_name);
println!("I am {} years old", my_age);
my_age += 1; println!("Next year I'll be {} years old", my_age);}

Coding Challenge

Now it’s time to make a similar program on your own. Make a program that outputs the following to the console:

My first cell phone was a <your_first_phone_model>
I got it in <year_you_got_phone>
Now I have a <your_current_phone_model>

Be sure to store the types of phone and the year you got your first one in variables — don’t just write them in the output string. Also, only use one variable for the type of phone and reassign its value. Bonus points if you can use a variation on println! from this article.

Be sure to share you only solution in the comments and compare with others!

Afterward: What about Rust’s const keyword?

Some of you might have already heard that Rust has it’s own const keyword and you might wonder why it wasn’t covered here. The reason is that Rust’s const exists for a specific use case that’s difficult to understand without first learning about lifetimes and ownership. Don’t worry! We’ll look into const in a later article after we cover those topics.

I hope you all found that intro to Rust variables useful. If you have any questions, feel free to post them down below and if you found any mistakes be sure to point them out too so I can correct them. Happy coding!

--

--

Brian Heise

Full Stack web developer employed at Liferay Japan