Day 2/30 - Learning Rust 🦀

·

3 min read

Day 2/30 - Learning Rust 🦀

Welcome to Day 2 of our Rust journey! Today, we’ll dive into the fundamental concepts of variables, mutability in Rust. Let’s get started!

Variables and Mutability

1. Declaring Variables

In Rust, you declare variables using the let keyword. Variables are immutable by default, meaning their values cannot be changed once assigned. Here’s an example:

fn main() {
    let name = "Alice"; // Immutable variable
    println!("Hello, {}!", name);
}

2. Mutability

To create mutable variables, use the mut keyword:

fn main() {
    let mut age = 30; // Mutable variable
    age += 1; // Modify the value
    println!("Next year, I'll be {} years old.", age);
}

3. Constants

Constants are declared using theconst keyword and must have a fixed value at compile time.

const PI: f64 = 3.14159;
fn main() {
    println!("The value of PI is approximately {}.", PI);
}

Points to remember about rust variables:

  • By default, Rust variables are immutable.

  • If you try to reassign the values to variables,. If they are declared like this: let x = 5; then you will encounter an error like this:cannot assign twice to immutable variable x.

  • Although variables are immutable by default, you can make them mutable by adding mut in front of the variable name.

  • mutcannot be used in conjunction with constants. Not only are constants immutable by default, but they are immutable at all times. const declarations need the type of the value to be annotated, like:u32, and you use it instead of the let keyword.

  • Rust’s naming convention for constants is to use all uppercase with underscores between words. Ex: THREE_HOURS_IN_SECONDS

Shadowing

Shadowing means that it is possible to declare a new variable with the same name as an existing one. According to Rustaceans, when you use the variable name, the compiler will see the second variable since the first variable is shadowed by the second.

fn main() {
    let x = 5;

    let x = x + 1;

    {
        let x = x * 2;
        println!("The value of x in the inner scope is: {x}");
    }

    println!("The value of x is: {x}");
}

// Output
// The value of x in the inner scope is: 12
// The value of x is: 6

Another distinction between mut and shadowing is that when we use the let keyword again, we're essentially establishing a new variable, so we can modify the value's type while keeping its name the same.

    let spaces = "   ";
    let spaces = spaces.len();

There are two types of space variables: a numeric type for the second and a string type for the first. Because of shadowing, we can reuse the more straightforward spaces namess rather than having to think of new ones, like spaces_str and spaces_num . However, as demonstrated here, if we attempt to utilize mut for this, we will receive a compile-time error:

    let mut spaces = "   ";
    spaces = spaces.len();

The error says we’re not allowed to mutate a variable’s type.

$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
error[E0308]: mismatched types
 --> src/main.rs:3:14
  |
2 |     let mut spaces = "   ";
  |                      ----- expected due to this value
3 |     spaces = spaces.len();
  |              ^^^^^^^^^^^^ expected `&str`, found `usize`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `variables` due to previous error

Stay tuned for Day 3, where we’ll explore datatypes and functions. Happy coding! 🦀🚀

Did you find this article valuable?

Support Divyansh Mehta by becoming a sponsor. Any amount is appreciated!

Â