# Getting Started With Rust

lil_firelord
30.7K views

## 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
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
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX