Explore typed programs with ownership, borrowing and explicit error handling.

Before starting: Terminal use and an installed Rust toolchain.

Practice project: Handle valid and invalid integer input with Result.

Foundation and first practice

  1. Handle a parse result in Rust

    Rust represents many recoverable failures with Result rather than silently returning a usable value. A match expression makes the success and failure branches explicit. In this example a valid integer produces a number; invalid input produces an error branch. Learn this before relying on unwrap, which can panic on an error.

    Rust stable toolchain; standard library only

    fn main() {
        let input = "42";
        match input.parse::<i32>() {
            Ok(value) => println!("{}", value + 1),
            Err(_) => println!("Enter a whole number"),
        }
    }
    Check the output
    43

    Try a negative value and a number outside i32 range. Describe which part of the code handles the failure.

Trace changing state and check loop boundaries

A trace table records the state after each statement. It helps distinguish an incorrect algorithm from a syntax mistake. Write the input contract first: this example accepts a list of numbers and returns their sum. The initial total is zero, so an empty list returns zero.

Paper trace first; pseudocode is not executable. Use your chosen language compiler or interpreter for the implementation.

PSEUDOCODE — translate before running
total ← 0
FOR EACH value IN values
    total ← total + value
RETURN total
Check the output
[2, -1, 4] → 5
[] → 0
[7] → 7
The loop must process each element exactly once.

Trace [-3, 3] without running code. Then implement and test it. Explain why starting at the second element loses data. Reject non-number input or explicitly document that it is outside the input contract.

Open the Rust learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.