DEV Community

MAYUR KUMBHAR
MAYUR KUMBHAR

Posted on • Edited on

Rust Language Essentials: Variables, Constants, and Mutability Explained for Beginners

Continuing to our last post on the rust language fundamentals, today we will discuss on language foundations. What are variables, constants and Mutability works in Rust.

Understanding how to store and manage data is fundamental. Rust has specific rules around the variables and mutability that are key to its safety guarantees.

1. Variables with let :

  • Variables are declared using the let keyword:
let variable_name = value;
Enter fullscreen mode Exit fullscreen mode

Example:

let my_var = 5;
Enter fullscreen mode Exit fullscreen mode

2. Immutability by Default:

  • By default, variables in Rust are immutable. Once a value is assigned with let , it can not be changed.
  • This default behaviour helps prevent the accidental data modification and makes code easier to reason about.

3. Mutability with mut :

  • To allow a variable'd value to change, you must explicitly use the mut keyword:
let mut variable_name = value;
Enter fullscreen mode Exit fullscreen mode

Example:

let mut my_var = 123;
my_var = 345;
Enter fullscreen mode Exit fullscreen mode

4. Constants wit const :

  • Declared using the const keyword:
const NAME: Type = value;
Enter fullscreen mode Exit fullscreen mode
  • Always immutable, can not use mut with constants.
  • Must have their type annotated
  • Can only be set to a constant expression which is computable at compile time.
  • Often used for hardcoded values and conventionally named in UPPER_SNAKE_CASE.

5. Shadowing:

  • Declaring a new variable with the same name as previous one using let.
  • Example:
let x = 5;
let x = x + 1;
Enter fullscreen mode Exit fullscreen mode

The second x is a new variable shadowing the first.

  • Key difference from mut: Shadowing creates a new variable, allowing you to change the type of the bound to the name. mut changes the value in place but not the type.
  • Useful for transforming a value while reusing the variable name.

Variables in Rust store data, which can be of various basic data types like integers, floats, booleans, and characters ( we will cover this in more details in coming articles).

Rust's emphasis on immutability by default, combined with option of mut and feature of shadowing, provides fine grained control over data manipulation.

👉 Follow @themayurkumbhar on Medium

Top comments (0)