Activity 7 - Variables, Mutability, and Types Exploration
Part 1: Hypothesis Time
Working in groups, write down your predictions for each "What If" question below. Don't look anything up - just discuss and make your best guesses!
Binary and Number Representation
- What is 42 in binary?
- What decimal number is
1010 1100in binary? - In 8-bit two's complement, what would -5 look like?
Type Compatibility - Will These Compile?
For each code snippet, predict: ✅ Will compile or ❌ Won't compile (and why?)
-
#![allow(unused)] fn main() { let x: i32 = 42; let y: i16 = 100; let sum = x + y; } -
#![allow(unused)] fn main() { let price = 19.99; let tax_rate: f32 = 0.08; let total = price + (price * tax_rate); } -
#![allow(unused)] fn main() { let age: u8 = 25; let negative_age = -age; }
Shadowing
-
Are these equivalent? If yes, why, if not, what is different at the end?
let mut x = 5; x = 6;let x = 5; let x = 6;
-
Can you shadow with a different type? What will happen with:
#![allow(unused)] fn main() { let x = 5; let x = "hello"; } -
What will this print?
#![allow(unused)] fn main() { let x = 10; { let x = x + 5; println!("Inner: {}", x); } println!("Outer: {}", x); }
Overflow Behavior
- What happens when you overflow? Since
u8max is 255, what will this do?
#![allow(unused)] fn main() { let x:u8 = 250; println!("Outer: {}", x+10); }
Part 2: Test Your Hypotheses (15 minutes)
Now create a new Rust project and test your predictions! For each question, write code to test your hypothesis and record on your paper what you discovered:
- Was your hypothesis correct?
- What did you discover?
- Did anything surprise you?
Testing Strategy:
- Questions 1-3: Write code to convert/print binary representations
- Questions 4-6: Copy the code snippets and see if they compile
- Questions 7-10: Write small test programs to verify your predictions
Lab Notebook
Group members:
Notes
| Q | .................. Hypothesis ................... | .................. Discoveries .................. |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 | ||
| 4 | ||
| 5 | ||
| 6 | ||
| 7 | ||
| 8 | ||
| 9 | ||
| 10 |