DEV Community

Cover image for My #100DaysOfCode Journey: Day 3 in Rust
Aniket Botre
Aniket Botre

Posted on • Updated on

My #100DaysOfCode Journey: Day 3 in Rust

Greetings, fellow coders! πŸš€ As I progress through my #100DaysOfCode challenge with Rust, each day brings new revelations. If you missed my journey's beginning, catch up on LinkedIn Day 1 and LinkedIn Day 2. Now, let's dive into the highlights of Day 3, where variables, mutability, constants, and shadowing took center stage.

Variable Declaration in Rust

In Rust, the let keyword takes the stage for variable declaration:

let x = 5;
Enter fullscreen mode Exit fullscreen mode

Properties of Variables

  • Immutability: Variables are immutable by default. This means once a value is assigned, it cannot be changed.
  • Block Scoping: Following the trend of many programming languages, variables in Rust are block-scoped.
  • Naming Conventions: Snake case is the naming convention of choice for variables in Rust.

Mutability in Rust: Embracing mut

To add mutability, the mut keyword comes into play:

fn main() {
    let mut x = 5;
    println!("The value of x is: {}", x); // Prints 5
    x = 6;
    println!("The value of x is now: {}", x); // Prints 6
}
Enter fullscreen mode Exit fullscreen mode

Coming from a JavaScript background, I find it odd how Rust does the variable declaration. As in JavaScript letkeyword is used for declaring mutable variables and const keyword is used for declaring immutable variables.


Constants: Anchors in Code

Constants, declared with const, bring a fixed value into the coding landscape:

const MAX_POINTS: u32 = 100000;
Enter fullscreen mode Exit fullscreen mode

Note: While declaring constants type of the value must be annotated.

Why Constants?

While Rust defaults to immutability, constants serve as symbolic anchors, offering clarity and ease of maintenance. They provide a single point for updating hardcoded values across the codebase.


Shadowing: Unveiling New Realms

In Rust, when you reuse a variable name, the old one surrenders to the new in a phenomenon known as shadowing. It allows for the creation of a new variable, potentially changing its type:

let a = 23;
let a = a - 3;

{
    let a = a / 2;
    println!("The value of a in the scope is: {}", a);
    // Prints 10
}

println!("The value of a outside the scope is: {}", a);
// Prints 20
Enter fullscreen mode Exit fullscreen mode

Notably, shadowing opens doors to flexibility, enabling changes in variable types without the need for mutation.
As I navigate the nuances of Rust's variables and their characteristics, the language's emphasis on safety and expressiveness continues to shine through. Stay tuned for more Rust revelations on this coding adventure! πŸ’»πŸŒβœ¨


πŸš€ Explore My Daily Code Updates on GitHub!

My Github Repo

Top comments (0)