Chapter 2: The Rules of the Record (Data & Ownership)
In Chapter 1, we learned how to write a single note. But as you start writing more, you need a way to keep your "Record Book" organized. To keep your notes from getting mixed up or lost, Rust has a few "Golden Rules" for how information is handled.
1. The "Full Stop" Rule (The Semicolon ;)
In English, you end a sentence with a period so the reader knows you’re done talking. In Rust, you must end almost every instruction with a semicolon ( ; ).
Think of this as the Official Stamp. It tells the computer: _"This sentence is finished. Move to the next line."
fn main() {
let shares = 18; // ✅ Correct: The sentence is stamped and finished.
let price = 341; // ✅ Correct.
}
Did you notice the // in the code above?
This is called a Comment.
• The "Invisible Note": Anything you write after // is ignored by the computer.
• Why use it? It’s like writing a small note to yourself (or a teammate) to explain what the code is doing without the computer getting confused.
The Mistake: If you forget the semicolon, your rust-analyzer will turn the line red. It’s like a teacher rejecting your homework because you didn't finish your sentences.
2. The "Megaphone" Rule (Comma & Order)
When you use println! to shout out your results, you use {} as an Empty Seat for your data. But how does the computer know which data sits in which seat?
The Comma ( , ) is the separator.
Think of it like a line of people waiting to sit down. The first person after the comma takes the first seat {}. The second person takes the second seat {}.
The "Transaction" Example:
fn main() {
let balance = 6000;
let withdrawn = 1000;
// The order matters!
// 'balance' goes to the 1st {}, 'withdrawn' goes to the 2nd {}.
println!("Balance is {} and amount withdrawn is {}", balance, withdrawn);
}
Output: Balance is 6000 and amount withdrawn is 1000
Key Rule: If you have two seats {} {}, you must have two names after the comma, separated by another comma. If the order is wrong, your sentence won't make sense!
3. Telling the Difference: Numbers vs. Sentences
Imagine you are writing a message to a friend:
"Your current balance is 5000 rupees. I am giving you 1000 rupees, so your total will be 6000."
In English, that is just one long sentence. But in Rust, if we want the computer to actually calculate that total (add, subtract, or divide), we have to separate the "Label" from the "Math."
The Code Example:
fn main() {
let mut balance = 5000; // This is a number we can do math with
let incoming_cash = 1000;
balance = balance + incoming_cash; // The computer adds them up!
println!("Your total will be {}", balance);
}
In the code we just wrote, we used: let mut balance = 5000;. Here we let the computer guess the data type—quite convenient, right?
But there is a catch. In real programming, we almost never recommend relying on the guess. Let’s take a look at why automatic guessing is dangerous through a serious question:
Can a physical cash balance ever be negative? No. You either have money, or you have zero. But since the computer just sees 5000 as a generic number, its "guess" will allow a mistake like this:
fn main() {
let mut balance = 5000;
let withdrawn = 6000; // Oops, we withdrew more than we have!
balance = balance - withdrawn;
println!("Current Balance: {}", balance); // This will print -1000!
}
In the real world of Finance, a "negative" cash record is a disaster. If we let the computer just guess, it creates a security hole where "ghost" negative numbers can ruin your records.
But why did the computer allow a negative number in the first place? Because when Rust guesses, its default choice is a flexible container called i32, which allows both positive and negative numbers. (We will look at exactly what i32 means in just a moment in Point 4: Choosing the Right "Box"). While i32 is great for tracking debt or freezing temperatures, using it for a strict physical cash balance is exactly how mistakes happen!
How do we solve this? (The Explicit Guardrail)
This is exactly why Rust is famous for being a Safe Language. To prevent these "ghost" numbers, we use a feature called the Explicit Guardrail.
Instead of letting the computer guess its default i32, you become the boss. We add a "Category" or "Data Type" right after the name to set the strict rules. In this case, we use a positive-only "Safe" called u32.
fn main() {
// We add ': u32' to tell Rust this is a POSITIVE-ONLY safe
let mut balance: u32 = 5000;
let withdrawn = 6000;
// Rust will now STOP the program before it ever saves a negative number!
balance = balance - withdrawn;
}
What exactly is a u32?
Think of it as a label on a storage box that tells you two things:
• The u (Unsigned): This means "No Minus Sign allowed." It is a positive-only box.
• The 32 (Bits): This is the size of the box. A 32-bit box is a standard "Safe" that can hold any whole number from 0 up to 4,294,967,295 (over 4 billion!).
By using u32, you are setting a guardrail. If a calculation tries to go below zero, Rust will literally crash the program on purpose rather than letting a dishonest or wrong number enter your record book.
Important Note: In a real bank, if you try to transfer more money than you have, the whole bank doesn't "crash"—it just sends you a message saying "Insufficient Funds." >
Currently, our simple code is like a very strict security guard who shuts down the whole building if he sees a mistake. Don't worry, though! Later in this book, we will learn how to handle these errors gracefully (using a tool called the Match function) so your program can stay running while simply saying "Transaction Declined."
4. Choosing the Right "Box" (Numbers)
Depending on how many "zeros" your transaction needs, you can pick different sizes of these positive-only (u) or flexible (i) safes:
• u8 (The Tiny Drawer): Holds positive numbers from 0 to 255. (Great for small things like age or your 18 shares).
• u32 (The Standard box): Holds positive numbers up to 4 Billion. (Perfect for bank balances).
• i32 (The Flexible Wallet): The i stands for "Integer," but you can think of it as "Inclusive." It allows for both positive and negative numbers. It can hold any number from -2,147,483,648 to 2,147,483,647. Use this if you need to record a loss or a debt!
Note: Just like in a hardware store, these boxes come in all sizes! We also have i8, i16, i64, and u16, u64. The bigger the number in the name, the more "zeros" the box can hold.
5. Choosing the Right "Box" (Text)
Now that we know how to store numbers, how do we store words? In English, a word is just a word. But in Rust, we have two main types of "Text Boxes" depending on whether the text is Fixed or Flexible.
A. The "Printed Label" (&str)
Think of this as a label that is printed directly onto a physical object. Once it’s printed, you can't add more letters to it or change the font.
• The Rule: It is a fixed piece of text. It stays exactly as it was written when the program started.
• Code: let greeting = "Hello"; (Rust automatically makes this a &str).
B. The "Writing Notebook" (String)
This is for text that needs to be flexible. It’s like a notebook where you can keep writing more lines, erase things, or tear pages out. This box can grow as large as you need it to.
• Code: let mut name = String::from("my balance");
• The Rule: Notice the Capital S in String. In Rust, a String is a "Big Deal"—it's a complex structure, so it gets a capital letter to show its importance.
• The :: (The Menu Path): Why String::from? Think of the :: as navigating a menu in your favorite app. It’s exactly like opening your Notes App -> clicking the 3 dots at the top -> and selecting the "Create New Note" option. You are telling Rust: "Go to the String category -> open the from tool -> and create a new notebook using these words."
It’s exactly like opening your Notes App -> clicking the 3 dots at the top -> and selecting the "Create New Note" option.
You are telling Rust: "Go to the String category -> open the from tool -> and create a new notebook using these words."
🛠️ Try it Yourself!
Open your VS Code and try to create your own "Digital Record." Copy this code and see if you can change the values. Try to make the balance a negative number and see if the "Guardrail" we talked about actually stops you!
fn main() {
// 1. Create a positive-only number for your balance
let balance: u32 = 10000;
// 2. Create a flexible String for your name
// Remember: Capital 'S' and '::' to call the tool!
let name = String::from("Your Name");
// 3. Shout it out!
println!("Hello {}, your current balance is {} rupees.", name, balance);
}
6. Where is the Data Stored? (The Warehouse)
Now that you know what kind of Boxes we use (u32 for numbers, String for text, etc.), we need to look at where these boxes are actually kept.
When you run a program, the computer doesn't put your active data on the SSD (the slow, long-term storage like a filing cabinet). It puts it in the RAM (the fast, short-term storage like your desk).
However, even inside the RAM, Rust is very picky about organization. It divides your desk into two sections:
The Custom Bookshelf (The Stack)
• What goes here? Small, fixed-size items like your u32 or u8 numbers, and your Printed Labels (&str).
• Why? Imagine you are designing a custom cupboard or a bookshelf. If you know exactly how thick every single book is, you can build the shelves to fit them perfectly. In Rust, because a u8 box has a strict maximum limit (255), the computer knows exactly how much space to carve out. It stacks them back-to-back perfectly. Because there are no surprises and no wasted space, finding and grabbing these items is lightning-fast! It’s like picking up a book directly from the shelf right next to your desk to study. It’s quick, isn't it?The College Bag (The Heap)
• What goes here? Large, flexible items like your String notebooks.
• Why? Think of this like your college bag or a big storage cupboard. You don't know exactly how many books you will need to carry until you get your timetable for the day. Some days your bag is packed with heavy textbooks, and other days it's almost empty. Because the size is always changing, you can't shove it into a strict, perfectly measured custom shelf—it would break! Instead, Rust finds a big, open space on the "Main Floor" (the Heap) to store it, where it has plenty of flexible room to grow or shrink safely based on your timetable.
7. "Where is my Bag?" (Connecting the Shelf to the Floor)
We have a slight problem. Your heavy College Bag (the flexible String) is sitting somewhere on the massive main floor of the RAM (The Heap). But when you are sitting at your desk, how do you find it instantly without searching the whole room? You might logically ask the computer: "Where is my bag?"
Rust solves this using a tiny Index Card (in programming, this is called a Pointer).
How the Index Card Works
Even though the big, flexible bag is out on the floor, Rust writes a tiny, fixed-size Index Card and places it right on your fast Custom Bookshelf (The Stack).
This Index Card contains three crucial pieces of information:
• The Address: Where exactly is the bag located on the main floor?
• The Length: How many books are currently in it?
• The Capacity: How many books can the bag hold before it tears?
Because this Index Card is small and its size never changes, it fits perfectly on your fast bookshelf. When your code says, "Print my String!", the computer quickly grabs the Index Card from the shelf, follows the address to the heavy bag on the floor, and reads what's inside.
8. The Golden Rule: "One Manager" (Ownership)
This brings us to the ultimate boss level of Rust. This is the exact feature that makes it a top-tier "Safe Language" for cybersecurity and finance.
Imagine you and your brother are sharing that College Bag. If you both have an Index Card pointing to the exact same bag, chaos happens:
• What if you try to pull a book out while he is trying to put one in?
• What if he decides to empty the whole bag and throw it away, but your Index Card still says it's there?
In the computer world, if two parts of a program try to change or delete the same bag at the same time, it causes a massive crash (hackers actually use this exact confusion to break into systems!).
To prevent this, Rust enforces the strict Rule of Ownership:
Only ONE variable can hold the Index Card for a bag at any given time.
The Handover (Moving Ownership)
Let's see this in action:
fn main() {
let my_slip = String::from("Paras"); // You own the Tracking Slip to the bag.
// Now, you give the slip to your brother:
let brother_slip = my_slip;
// If you try to use my_slip now, Rust will STOP the program!
// println!("{}", my_slip); // ❌ ERROR! Your hands are empty!
}
When you write let brother_card = my_card;, you aren't buying a whole new bag and copying all the books. That would waste too much time and RAM!
Instead, you physically hand over the Index Card. Because you gave it away, your hands are now empty. Rust immediately crosses off your name. If you try to read your card again, Rust throws an error because you no longer own the data. This guarantees that no two people can ever fight over the same bag.
🛠️ Try it Yourself: The "Handover" Error
Reading about the Index Card is one thing, but seeing Rust catch you in the act is where the magic happens. Let's force an Ownership error!
Open your VS Code, delete whatever is in your main.rs file, and paste this exact code:
fn main() {
// 1. You create the heavy bag and hold the Index Card
let my_card = String::from("My Heavy College Bag");
// 2. You physically hand the Index Card to your brother
let brother_card = my_card;
// 3. Now, try to read YOUR card to see what's inside...
println!("My card says: {}", my_card);
}
What happened?
The moment you paste this, your rust-analyzer will light up with a red squiggly line under my_card inside the println! statement.
If you hover your mouse over the red line, Rust will give you an error message that says something like: "value borrowed here after move."
What does that actually mean?
• "Move": Rust is saying, "Hey, you moved the Index Card to brother_card on line 5!"
• "Borrowed here": Rust is scolding you: "On line 8, you tried to look at an Index Card that you already gave away. Your hands are empty!"
How to fix it?
Since your brother holds the card now, only he can tell you what is in the bag. Change the println! to ask him instead:
fn main() {
let my_card = String::from("My Heavy College Bag");
let brother_card = my_card;
// Ask the person who actually holds the card!
println!("Brother's card says: {}", brother_card);
}
Instantly, the red line disappears! You have just successfully navigated Rust’s strictest security rule.
Chapter 2 Wrap-Up: The Master Record
We covered a massive amount of ground in this chapter. You didn't just learn how to write code; you learned how a computer actually thinks and manages its memory! Let’s review the Golden Rules of your new digital record book:
• The Official Stamp & The Megaphone: Every code sentence must end with a semicolon (;). When you want to shout out a result using println!, the comma separates your data, and they take their {} seats in exact order.
• The Guardrails (Data Types): We never let the computer guess! We explicitly label our boxes. We use u32 to prevent negative "Ghost Balances," and we use String for flexible, growing text (like a Writing Notebook).
• The RAM Warehouse (Stack vs. Heap): * Small, fixed-size items go on the Custom Bookshelf (The Stack) because the computer can grab them instantly.
• Large, unpredictable items go on the Main Floor (The Heap), just like throwing a flexible College Bag into a big open room.
• The Golden Rule (Ownership): To keep track of the College Bag on the main floor, Rust puts a tiny Index Card on your fast Bookshelf. To keep your data perfectly safe, only one variable can hold that Index Card at a time. If you hand it to someone else, your hands are empty!
⏭️ Sneak Peek: Chapter 3 (The Art of Lending)
What if a friend just wants to look at your notebook? You shouldn't have to permanently give away your property just to share information!
In Chapter 3, we will unlock the next level of Rust: Borrowing. You will learn how to "Lend" data securely without breaking the Golden Rule. We will also learn how to politely handle errors (like "Transaction Declined") without crashing the system!
💡 Pro Tip for the Road
Open VS Code and try to break the rules on purpose! Put a negative number in a u32 box, or try reading an Index Card after you hand it over. Seeing those red errors pop up is the fastest way to learn.
See you in Chapter 3!!!
Top comments (0)