Getting Started With Rust

lil_firelord
1,628 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Binding Variables in Rust

Rust refers to all declarations as Bindings as they bind a name you create to some type of data. All bindings begin with let.

let x = 1;

This will bind x to the value of 1.

Rust has strong type inference so we did not have to specify what type x would be, the compiler automatically figured it out. However we can easily declare the type by adding : type after our variable name:

let x: i32 = 1;

The above code behaves exactly the same, however we specifically told the compiler that x will be of type i32 which is a signed 32-bit integer. (We will go over all of Rust's built-in data types in the next section).

In simple examples like this, declaring a type is not necessary, however as your code gets more complex, the compiler may need you to specify what type you intend to use. Additionally, it can be a good habit to comment the type after you bind it.

Rust has two types of comments

  • Line Comments: // Which tells the compiler to skip anyhing after the // on the same line
  • Doc Comments: /// These are mainly for writing documentation for you code and support markdown.

Using the above example we could write something like:

let x = 1; // x: i32

Mutability

By default, all bindings in rust are immutable. If you're not familiar with the term, its basically means whether the variable can be changed, or mutated, after it's bound.

This is NOT ALLOWED and will give a compiler error:

let x = 1;
x = 3; // This will give a compile error since x is immutable by default

In order to be able to re-assign a value later, we need to initially bind it with the mut keyword like such:

let mut x = 1;
x = 3; // This is allowed since we marked x as mutable.

Playground

Variables
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main() {
let x: i32 = 1;
let y = 3; // i32
let mut z = 10; // mut i32
println!("Before reassignment: x is {}, y is {}, and z is {}", x, y, z);
z = 12; // This is valid
//x = 7; This is invalid and won't compile
println!("After reassignment: x is {}, y is {}, and z is {}", x, y, z);
let mut greeting = "World";
println!("Hello {}!", greeting);
greeting = "lil_firelord";
println!("Hello {}!", greeting);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

On To Control Flow

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content