Variables

Consider the following example around variable assignment in C#:

int x = 5;

And the same in Rust:

let x: i32 = 5;

So far, the only visible difference between the two languages is that the position of the type declaration is different. Also, both C# and Rust are type-safe: the compiler guarantees that the value stored in a variable is always of the designated type. The example can be simplified by using the compiler's ability to automatically infer the types of the variable. In C#:

var x = 5;

In Rust:

let x = 5;

When expanding the first example to update the value of the variable (reassignment), the behavior of C# and Rust differ:

var x = 5;
x = 6;
Console.WriteLine(x); // 6

In Rust, the identical statement will not compile:

let x = 5;
x = 6; // Error: cannot assign twice to immutable variable 'x'.
println!("{}", x);

In Rust, variables are immutable by default. Once a value is bound to a name, the variable's value cannot be changed. Variables can be made mutable by adding mut in front of the variable name:

let mut x = 5;
x = 6;
println!("{}", x); // 6

Rust offers an alternative to fix the example above that does not require mutability through variable shadowing:

let x = 5;
let x = 6;
println!("{}", x); // 6

C# also supports shadowing, e.g. locals can shadow fields and type members can shadow members from the base type. In Rust, the above example demonstrates that shadowing also allows to change the type of a variable without changing the name, which is useful if one wants to transform the data into different types and shapes without having to come up with a distinct name each time.

See also: