Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Activity 14: Confidence check

Name:

Midterm 1 is Friday. This week you also sit down with a CA and talk about your Project 1 code.

This sheet is not a quiz. You don't actually answer anything. Just read each line and mark how you feel about it, then keep the paper and study from the third column.

Mark one box per row:

  • Got it. I could do this right now, on paper, with nobody helping.
  • Shaky. I would get there, but I would be slow or I would second-guess it.
  • Study it. I need to go back to this before Friday.

Everything here is from Lectures 1 through 13. Nothing new from today's lecture (L14) is on the midterm.

Part 1: Tools

Could you do this?Got itShakyStudy it
1.1Move into a directory and list everything in it, hidden files included
1.2Rename a file, then delete it
1.3Send a command's output into a file instead of the screen
1.4See what you have changed but not yet staged in git
1.5Make a branch, commit on it, and push it
1.6Undo a commit that is already pushed
1.7Say how cargo build is different than rustc, and what --release changes

Part 2: Rust, line by line

Could you do this?Got itShakyStudy it
2.1Make a variable changeable
2.2Shadow a variable
2.3Define a constant
2.4Find the largest value of an i8 and a u8
2.5Say what could happen when an i32 addition goes past its maximum
2.6Say why you cannot add a u32 to an i32, and what to do about it
2.7Write a function that hands back two values at once
2.8Say whether something is a statement or an expression
2.9Pick between loop, while, and for, and defend your choice
2.10Break out of a loop, and skip to the next pass through it
2.11Choose between &self, &mut self, and self on a method
2.12Write a constructor, and say why it is Thing::new and not thing.new
2.13Say what the compiler does when a match misses a variant
2.14Use Option instead of a stand-in value like -1
2.15Choose between panic! and returning a Result, and defend the choice
2.16Use ?, and say what it needs from the function's return type

Part 3: Read the code

Again, don't answer these completely - just decide whether you could.

3.1 What does this print?

#![allow(unused)]
fn main() {
let x = 5;
let x = x + 1;
{
    let x = x * 2;
    println!("inner: {x}");
}
println!("outer: {x}");
}

3.2 Does this compile? If not, what is the error and what is the fix?

#![allow(unused)]
fn main() {
let a: u32 = 5;
let b: i32 = 3;
println!("{}", a + b);
}

3.3 Does this compile? If not, what is the error and what is the fix?

#![allow(unused)]
fn main() {
fn double(n: i32) -> i32 {
    n * 2;
}
}

3.4 What does this print?

#![allow(unused)]
fn main() {
let scores = [90, 75, 88, 62];
let mut total = 0;
for s in scores {
    if s < 80 {
        continue;
    }
    total += s;
}
println!("{total}");
}
Got itShakyStudy it
3.1
3.2
3.3
3.4

Part 4: Write it from nothing

On paper, no compiler, no notes. Could you do it?

Could you write this?Got itShakyStudy it
4.1Given struct Counter { hits: u32 }, a method that adds one to hits and a method that reports whether hits is over 10
4.2A recursive function that adds up the digits of a u32
4.3An enum for a traffic light where one variant carries a number of seconds, and a match over it
4.4A function that divides two numbers and gives back a Result, with an error when the divisor is zero

Part 5: Say it out loud

Could you explain this to someone?Got itShakyStudy it
5.1Why merge sort is O(n log n)
5.2What's the difference between a compiled and an interpreted language
5.3Why we don't distinguish O(3n^2 + 500n) from O(n^2)
5.4How many bits are in a byte
5.5What every recursive function needs, and what happens without it

Part 6: Prep and reflect

Some things to reflect on.

1. Which part of your Project 1 would you least like to be asked about this week? (And what can you do to prepare?)




2. Of everything you marked "Study it", which do you think will be more important to review?



Before you go

Take a photo of both sides and upload it. Then keep the paper so it can help guide your studying.

Solutions

One-line answers. If yours is longer and says the same thing, it is right.

Part 1

  • 1.1 cd dir, then ls -a. ls -la also shows permissions and sizes
  • 1.2 mv old.txt new.txt to rename, then rm new.txt to delete. mv does double duty as rename and move
  • 1.3 command > out.txt. A single > replaces the file, >> adds to the end of it
  • 1.4 git diff. Staged changes are git diff --staged, and git status names the files without showing the contents
  • 1.5 git switch -c name, commit, then git push -u origin name. The -u is what makes later pushes on that branch just git push
  • 1.6 git revert <hash>, which makes a new commit undoing that one. Safer than deleting history, because anyone who already pulled still has a history that matches yours
  • 1.7 cargo reads Cargo.toml, fetches your dependencies, and builds the whole project; rustc compiles the one file you point it at. --release turns on optimization, so it compiles slower and runs faster

Part 2

  • 2.1 let mut x = 5;
  • 2.2 Write let again with the same name: let x = x + 1;. That is a new variable, and it is allowed to have a different type. mut instead keeps one variable and changes its value
  • 2.3 const MAX_TRIES: u32 = 10;. Needs the type written out, has to be a value known at compile time, and is conventionally SCREAMING_CASE
  • 2.4 i8 tops out at 127, u8 at 255. Both hold 256 values, but i8 spends half its range on negatives
  • 2.5 Two different things depending on the build. Debug panics with "attempt to add with overflow"; release wraps around silently. Same code, two behaviors
  • 2.6 Rust does no implicit numeric conversion. Cast with as, or declare both the same type. as can lose information, so it is a choice you are making on purpose
  • 2.7 Return a tuple: -> (u32, u32), then (a, b). Destructure at the call site with let (x, y) = ...
  • 2.8 An expression evaluates to a value; a statement does not. A trailing semicolon turns an expression into a statement, so the value is thrown away
  • 2.9 for when you know the collection or the count, while when you have a condition, loop when you will break out yourself
  • 2.10 break leaves the loop, continue jumps to the next pass
  • 2.11 &self to read, &mut self to change, self to consume. A method that changes the struct and is declared &self will not compile
  • 2.12 fn new(...) -> Self, with no self parameter, so it is an associated function rather than a method. :: because there is no instance yet to put on the left of a dot
  • 2.13 It refuses to compile, and names the variant you missed. That is the payoff of an enum: add a variant and the compiler finds every match that now needs updating
  • 2.14 Option<T> makes "nothing" a separate case the compiler forces you to handle. -1 is a real number that happens to mean something else, and it can be used by accident
  • 2.15 Panic when the situation is a bug in your own code and carrying on makes no sense. Return a Result when the caller could reasonably recover, such as a missing file or bad input
  • 2.16 ? hands back the value on success, and on failure returns the error out of the current function. So the function itself has to return Result or Option

Part 3

  • 3.1 inner: 12, then outer: 6. The first shadow makes x 6; the inner block shadows again to 12, and that binding ends with the block
  • 3.2 No. Mismatched types on a + b. Cast, a + b as u32, or declare both the same type. Note b as u32 would wrap if b were negative
  • 3.3 No. expected i32, found (). The semicolon after n * 2 throws the value away. Delete it, or write return n * 2;
  • 3.4 178. 90 and 88 are added, 75 and 62 are skipped

Part 4

  • 4.1 fn bump(&mut self) { self.hits += 1; } and fn is_hot(&self) -> bool { self.hits > 10 }. The point is the two different receivers
  • 4.2 Base case if n < 10 { return n; }, then n % 10 + digit_sum(n / 10)
  • 4.3 enum Light { Red, Green, Yellow(u32) }, then a match with a Light::Yellow(secs) => arm binding the payload. Missing a variant is a compile error
  • 4.4 fn divide(a: f64, b: f64) -> Result<f64, String>, returning Err(...) when b == 0.0 and Ok(a / b) otherwise

Part 5

  • 5.1 The call tree has log n levels, because the list halves each time, and every level does n work merging back together. n per level times log n levels
  • 5.2 A compiler translates the whole program to machine code once, ahead of time, and can optimize across the whole thing. An interpreter works out what to do line by line every time it runs
  • 5.3 Constants drop and lower-order terms drop, because for large enough n the n^2 term is what decides the answer. At n = 1000 the n^2 term is 3,000,000 and the other is 500,000
  • 5.4 Eight
  • 5.5 A base case that returns without recursing, and a call that moves toward it. Without both, it recurses until the stack runs out

Part 6 has no answers. It is reflection, and question 2 is the one to aim your studying with.