Activity 6: Variables, Mutability, and Types Exploration
Part 1: Hypothesis Time
You can work solo or in groups, but EACH person 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 63 in binary (hint: it's 64-1)?
- What decimal number is
1100in binary (if it's positive)? - In 4-bit two's complement, what would -4 look like?
Type Compatibility - Will These Compile?
For each code snippet, predict: will it compile? (Why or why not?)
-
#![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
Now visit Rust Playground 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: Skip checking, we'll go over it together
- Questions 4-6: Copy the code snippets and see if they compile
- Questions 7-10: Write small test programs to verify your predictions
Solutions
111111. Six ones, because 64 is 2^6 and 63 is one less121100. The same bits as question 2, which is the point: you need to know what type something is to know how to interpret the bits- No. E0308 mismatched types, then E0277, cannot add
i16toi32. Needsx + y as i32 - Yes, and
totalis21.5892.pricehas no written type, and multiplying by anf32makes it one - No. E0600, cannot apply unary
-tou8, "unsigned values cannot be negated". Switching toi8compiles - Both compile and both end at 6.
mutreuses one variable, shadowing makes a second that hides the first - Yes, prints
hello. Shadowing can change the type,mutcannot Inner: 15thenOuter: 10. The innerletis a newxthat dies with the block.- No, it does not even compile:
deny(arithmetic_overflow)catches it because the compiler can do the sum itself. Only when the value arrives at runtime do you get a panic (behavior here might differ between compiler modes and on the playground).