Rust for the Novice Programmer/Variables

Variables edit

What if we wanted to not have the calculation inside the println!() line.

To solve this, we can use variables. Variables allow you to store values for later use.

Here's an example:

 let number = 5;

First, 'let' is a special keyword that means the thing is a variable. 'number' here is the name of the variable so we can refer to it later. '=' shows we are putting in the variable. the 5 is the value we are putting in. This means that later when we put in 'number', it will refer to the number 5. The semicolon ; is as before, indicating the end of the line.

For example

 let number = 5;
 println!("{}", number);

will print out the 5 we put into 'number'.

Why is this good?

The advantage of this is now we have the value separated out it is easier to change. So we could change the line to

 let number = 5 + 4;

and the println() line would print out the new value of number, which is 9.

Changing Variables edit

One interesting thing about Rust is that variables are immutable by default. This means they cannot be changed after being created. However, you can set a variable as mutable(able to be changed) by using the 'mut' keyword.

 let mut number = 5;
 number = 8;
 println!("{}", number);

This will print out the value 8 since it overrides the value 5 and in fact the value 5 does absolutely nothing here. If you run this, the compiler will tell you 'warning: value assigned to `number` is never read' since it is quite smart but also quite pedantic in checking for strange things in your code.

If you did want to put the variable earlier but put the value later you could do this:

 let number;
 number = 8;
 println!("{}", number);

Note that number no longer needs to have 'mut' since it is only being set to a value once so it is not being changed. However, you cannot use it before you set a value to it. For example,

 let number;
 println!("{}", number);
 number = 8;

This will give you an error when you run 'cargo run' on it since the compiler works out number doesn't have a value in it when you try to print it.

Here are some things you can do with changing variables:

You can do mathematical equations in order:

 let mut x = 10;
 x = x * x;
 x = x + 5;
 println!("{}", x);

Here we have a variable with the name 'x'. This is shorter and easier to type, but is less descriptive so might not tell you or other people what this number is for later. Also note we are using the last value of x each time we set the next value of x. This computes x2 + 5 with x = 10, which gives 105. You can change the x value and it will compute the same equation for the different values of x.

One last thing for now: that x = x * number or x = x + number is quite a common thing to do, so there is a way to shorten this:

 let mut x = 10;
 x *= x;
 x += 5;
 println!("{}", x);

This program does the same thing. For the basic operations, you can use them with '=' to shorten it.

Next up: Comments