Rust Tutorials: Understanding the `let` Keyword

beginner
18 min

Rust Tutorials: Understanding the let Keyword

Welcome to our comprehensive guide on Rust! In this lesson, we'll delve into the let keyword, one of the fundamental building blocks of Rust programming. Let's get started! 🎯

Introduction

In Rust, the let keyword is used to declare and initialize variables. Variables in Rust are crucial for storing data and manipulating it during the course of your program. Let's create our first variable! 📝

rust
let my_first_variable = 10;

In the above example, we've declared a variable named my_first_variable and initialized it with the value 10.

Variable Types

Rust is a statically-typed language, which means that every variable has a specific type associated with it. Rust will automatically infer the type based on the value you're assigning. For example, in the code above, my_first_variable is inferred to be of type i32 (32-bit signed integer).

Shadowing Variables

You can redeclare a variable using the let keyword, a process known as shadowing. When you shadow a variable, you're essentially creating a new variable with the same name but a different scope. Here's an example:

rust
let my_first_variable = 10; let my_first_variable = 20;

In the above example, we've created a new my_first_variable with the value 20, effectively shadowing the original my_first_variable with the value 10.

Constants

While the let keyword is used for variables, Rust also provides a const keyword to declare constants. Constants are immutable values with a global scope. Here's an example:

rust
const PI: f64 = 3.14;

In the above example, we've declared a constant PI with the value 3.14 and the type f64 (64-bit floating-point number).

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of the `let` keyword in Rust?

Stay tuned for our next lesson where we'll explore functions and control structures in Rust! 💡