Variables, Constants, and Data Types
# CHAPTER 4
Variables, Constants, and Data Types
1. Chapter Introduction
In this chapter, we will learn how to store and manipulate data in Rust. Rust handles variables very differently from languages like Python or JavaScript. To ensure safety and prevent bugs, variables in Rust are Immutable (unchangeable) by default. We will explore how to override this behavior, how to define Constants, and survey the fundamental Data Types that Rust provides.2. Learning Objectives
By the end of this chapter, you will be able to:-
Declare variables using the
letkeyword.
- Understand and utilize Immutability by default.
-
Make variables mutable using the
mutkeyword.
-
Declare Constants using
const.
- Differentiate between Scalar types (integers, floats, booleans, chars) and Compound types (tuples, arrays).
3. Variables and Immutability
To declare a variable in Rust, use thelet keyword.
CRITICAL RULE: By default, once a value is bound to a variable name, you cannot change it! This is called Immutability. It makes your code incredibly safe, especially in multi-threaded programs.
If you want a variable to be changeable, you must explicitly add the mut (mutable) keyword.
4. Constants
Constants are values that are bound to a name and are *never* allowed to change. Differences betweenlet and const:
-
1.
You use
constinstead oflet.
-
2.
You CANNOT use
mutwithconst.
- 3. You MUST explicitly declare the data type.
-
4.
Constants can be declared in the global scope (outside of
main).
5. Data Types in Rust
Rust is a Statically Typed language, meaning it must know the types of all variables at compile time. Usually, the compiler can infer the type based on the value, but sometimes we must specify it explicitly.#### A. Scalar Types A scalar type represents a single value. Rust has four primary scalar types:
1. Integers (Whole numbers)
-
Signed (can be negative):
i8,i16,i32,i64,i128,isize
-
Unsigned (positive only):
u8,u16,u32,u64,u128,usize
i32)*
2. Floating-Point Numbers (Numbers with decimals)
-
f32(Single precision)
-
f64(Double precision)
f64)*
3. Booleans
Can only be true or false.
4. Characters (char)
Represents a single Unicode value (uses single quotes).
#### B. Compound Types Compound types group multiple values into one type. Rust has two primitive compound types:
1. Tuples Group values with a *variety of different types* into one compound type. Tuples have a fixed length.
2. Arrays Group multiple values of the *exact same type*. In Rust, arrays have a fixed length (they cannot grow or shrink).
6. Variable Shadowing
You can declare a new variable with the same name as a previous variable. This "shadows" the original variable, effectively replacing it. Unlikemut, shadowing allows you to change the *Data Type*.
7. Common Mistakes
-
Mutating a non-mut variable: Trying to change a variable declared with just
letis the most common beginner error.
-
Out of bounds Array access: Attempting to access
numbers[10]on an array of length 5 will cause the program to "panic" (crash) safely, rather than allowing hackers to read arbitrary memory like in C/C++.
-
Mismatched types: Rust will NOT automatically convert a float to an integer. You cannot do
let x: i32 = 5.5;.
8. Best Practices
-
Embrace Immutability: Only use
mutwhen you absolutely need to. Code with immutable variables is easier to read, test, and run concurrently without bugs.
-
Let the compiler infer types: You don't need to write
let x: i32 = 5;. Just writelet x = 5;and let Rust figure it out to keep your code clean.
9. Exercises
-
1.
Create a mutable integer
scoreset to 0. Add 10 to it and print it.
-
2.
Create a constant
PIwith the value 3.14159.
-
3.
Create a tuple representing a 3D coordinate (x, y, z) and print the
yvalue using dot notation.
10. MCQs with Answers
By default, variables in Rust are:
Which keyword allows a variable to be changed?
How do you declare a constant in Rust?
What is the default integer type in Rust if not specified?
What Compound type allows you to group variables of DIFFERENT data types?
How do you access the first element of a Tuple named my_tuple?
What feature allows you to declare a new variable with the same name as a previous one, even changing its data type?
Which scalar type represents a single Unicode character enclosed in single quotes?
let age: u8 = -5;?
a) Yes b) No, because u8 is an unsigned integer and cannot be negative
Answer: b) No, because u8 cannot be negative.
11. Interview Questions
-
Q: Explain the difference between
mutand Shadowing.
- Q: Why did the creators of Rust make variables immutable by default?
- Q: What is the difference between an Array and a Tuple in Rust?
12. FAQs
-
When should I use
i32vsu32? Usei32for general numbers that might be negative. Useu32(unsigned) when you want to mathematically guarantee the value can never drop below zero (like an age or a counter).
13. Summary
Rust's strict type system and immutability by default are the foundations of its safety guarantees. By forcing you to explicitly declare when data will change usingmut, Rust prevents accidental modifications. Understanding scalar and compound types allows you to organize data efficiently in memory.