PREDICT → IMPLEMENT → RUN → COMPARE → EXPLAIN

Write Rust. Run it locally.

Five small experiments, six unsolved functions. Predict, implement, run, compare, and explain.

  1. Predict
  2. Implement
  3. Run & test
  4. Compare
  5. Explain

00 · SETUP

Your editor and terminal are the lab

Download the educational ZIP below and extract it. No account or repository access is required. This page does not compile Rust; Cargo runs your code on your computer.

Download, extract, and check the tools

Run these commands from the folder containing rust-hands-on.zip. The workspace pins Rust 1.98.1. If cargo is missing from PATH, load its environment. If Rust is absent, use the official installation guide. Toolchain setup is separate; --offline prevents Cargo dependency downloads.

Download Rust practice ZIP

unzip rust-hands-on.zip
cd rust-hands-on
# Only if cargo is missing from PATH / PATHにない場合のみ:
source "$HOME/.cargo/env"
rustc --version
cargo --version
cargo test --offline -p fundamentals

Official Rust installation ↗

Create your own practice workspace

The script copies the unsolved library, tests, and runner to work/hands-on. It refuses to overwrite an existing folder. Edit work/hands-on/src/lib.rs; leave the source exercises intact. A newer download does not change your practice copy.

./scripts/start-practice.sh
cd work/hands-on
cargo run --offline --example practice

Expected: a list of six exercise IDs. You have not solved an exercise yet.

First run: TODO panic is expected

Select a single exercise before implementing it. Its todo!() compiles, then panics when called. A selected ignored test fails for the same reason. Use that real failure as your starting observation. The general check leaves unsolved tests ignored.

cargo run --offline --example practice -- ex01 Ada
cargo test --offline ex01 -- --ignored

crates/exercises/src/lib.rs · scripts/start-practice.sh are included in the ZIP.

01 · ex01

A function you can change

Return an owned String. An empty name returns こんにちは!; otherwise return こんにちは、名前!.

1 · Predict

What should Ada and an empty name produce? Does the input need to be modified?

Write the output or error you predict before running. Copy your observations to observations.md; this draft is cleared on reload.

2 · Implement

Implement only this function in src/lib.rs

pub fn greeting(_name: &str) -> String {
    todo!("ex01: greetingを実装する")
}

3 · Run & test

Run these in work/hands-on

cargo run --offline --example practice -- ex01 Ada
cargo run --offline --example practice -- ex01 ""
cargo test --offline ex01 -- --ignored

4 · Compare

Expected behavior after your implementation

Ada → actual = "こんにちは、Ada!"
empty → actual = "こんにちは!"

These are the specified expected results, not a claim that your local code has already produced them. No arguments uses the runner sample; test the empty slice with its unit test.

Stuck? Open one hint at a time

Hint 1

Separate the empty and nonempty cases with if. The last expression is the return value.

Hint 2

Use name.is_empty() to check the input. Both branches must return String, not &str.

Optional reference answer and explanation

Open after a real attempt. These answers are stored separately in hands-on/reference.rs and are never copied into the learner workspace. A passing test is evidence for its cases; explain the behavior and add a counterexample.

pub fn greeting(name: &str) -> String {
    if name.is_empty() {
        "こんにちは!".to_owned()
    } else {
        format!("こんにちは、{name}!")
    }
}

&str borrows the name. String owns the result. The function can create a new greeting while leaving the caller's name available. Explain why a semicolon on the final expression changes the return type.

5 · Explain

&str borrows the name. String owns the result. The function can create a new greeting while leaving the caller's name available. Explain why a semicolon on the final expression changes the return type.

Try a counterexample: Add a test with a Japanese name. Keep the contract's punctuation unchanged.

Read the corresponding textbook chapter →

Local textbook file in the ZIP: lessons/01-start.md

02 · ex02

Loop, branch, and integer width

Sum even i32 values, including negative values. Return i64 so a valid total can exceed i32.

1 · Predict

Predict [2, -4, 6], odd values only, and two copies of 2147483646. When must conversion happen?

Write the output or error you predict before running. Copy your observations to observations.md; this draft is cleared on reload.

2 · Implement

Implement only this function in src/lib.rs

pub fn sum_even(_numbers: &[i32]) -> i64 {
    todo!("ex02: sum_evenを実装する")
}

3 · Run & test

Run these in work/hands-on

cargo run --offline --example practice -- ex02 2 -4 6
cargo run --offline --example practice -- ex02 2147483646 2147483646
cargo test --offline ex02 -- --ignored

4 · Compare

Expected behavior after your implementation

[2, -4, 6] → actual = 4
[2147483646, 2147483646] → actual = 4294967292
[] → 0 (test)

These are the specified expected results, not a claim that your local code has already produced them. No arguments uses the runner sample; test the empty slice with its unit test.

Stuck? Open one hint at a time

Hint 1

Start an i64 accumulator at zero. Iterate over the borrowed slice and select values divisible by two.

Hint 2

Convert each selected value with i64::from(number) before adding it. Converting an already overflowed i32 total is too late.

Optional reference answer and explanation

Open after a real attempt. These answers are stored separately in hands-on/reference.rs and are never copied into the learner workspace. A passing test is evidence for its cases; explain the behavior and add a counterexample.

pub fn sum_even(numbers: &[i32]) -> i64 {
    let mut total = 0_i64;
    for &number in numbers {
        if number % 2 == 0 {
            total += i64::from(number);
        }
    }
    total
}

The slice is borrowed; each i32 is Copy. The accumulator needs mut because assignment changes it. Empty input naturally returns zero. Test width at the addition boundary, not only small positive values.

5 · Explain

The slice is borrowed; each i32 is Copy. The accumulator needs mut because assignment changes it. Empty input naturally returns zero. Test width at the addition boundary, not only small positive values.

Try a counterexample: Try negative even values and odd values only. Explain why the empty slice should not panic.

Read the corresponding textbook chapter →

Local textbook file in the ZIP: lessons/02-basics.md

03 · ex03 / ex04

Unicode and borrowed slices

Count Unicode scalar values, then return the portion before the first ASCII space as a borrowed &str. Leave the original String available.

1 · Predict

Does 日本語 have 3 bytes? What does a leading space return? Is e plus a combining accent one scalar value?

Write the output or error you predict before running. Copy your observations to observations.md; this draft is cleared on reload.

2 · Implement

Implement only this function in src/lib.rs

pub fn char_count(_text: &str) -> usize {
    todo!("ex03: char_countを実装する")
}

pub fn first_word(_text: &str) -> &str {
    todo!("ex04: first_wordを実装する")
}

3 · Run & test

Run these in work/hands-on

cargo run --offline --example practice -- ex03 日本語
cargo run --offline --example practice -- ex04 "日本語 練習"
cargo test --offline ex03 -- --ignored
cargo test --offline ex04 -- --ignored

4 · Compare

Expected behavior after your implementation

日本語 → bytes = 9; scalar_count = 3
日本語 練習 → borrowed = "日本語"; original = "日本語 練習"
same_start = true
e + combining accent → 2 scalar values (test)

These are the specified expected results, not a claim that your local code has already produced them. No arguments uses the runner sample; test the empty slice with its unit test.

Stuck? Open one hint at a time

Hint 1

str::len counts bytes. chars() visits Unicode scalar values. A borrowed word should refer to the original buffer.

Hint 2

find(' ') gives a byte index at a valid UTF-8 boundary. Slice up to it; when no space is found, return the input itself.

Optional reference answer and explanation

Open after a real attempt. These answers are stored separately in hands-on/reference.rs and are never copied into the learner workspace. A passing test is evidence for its cases; explain the behavior and add a counterexample.

pub fn char_count(text: &str) -> usize {
    text.chars().count()
}

pub fn first_word(text: &str) -> &str {
    match text.find(' ') {
        Some(end) => &text[..end],
        None => text,
    }
}

Scalar values, bytes, and user-perceived graphemes are different units. A slice has no new String allocation. The owner must outlive the borrowed result; Rust checks that relationship. ASCII-space splitting is the explicit contract, not a general word tokenizer.

5 · Explain

Scalar values, bytes, and user-perceived graphemes are different units. A slice has no new String allocation. The owner must outlive the borrowed result; Rust checks that relationship. ASCII-space splitting is the explicit contract, not a general word tokenizer.

Try a counterexample: Test no space, a leading space, an empty string, and a combining accent. Add a pointer equality assertion for a nonempty borrowed word.

Read the corresponding textbook chapter →

Local textbook file in the ZIP: lessons/04-borrowing.md

04 · ex06

Represent absence with Option

Return Some(largest value) for nonempty input and None for empty input. Do not invent a default maximum.

1 · Predict

What is the maximum of [-8, -2, -5]? What would starting a maximum at zero falsely imply?

Write the output or error you predict before running. Copy your observations to observations.md; this draft is cleared on reload.

2 · Implement

Implement only this function in src/lib.rs

pub fn maximum(_numbers: &[i32]) -> Option<i32> {
    todo!("ex06: maximumを実装する")
}

3 · Run & test

Run these in work/hands-on

cargo run --offline --example practice -- ex06 -8 -2 -5
cargo test --offline ex06 -- --ignored

4 · Compare

Expected behavior after your implementation

[-8, -2, -5] → actual = Some(-2)
[] → None (test)

These are the specified expected results, not a claim that your local code has already produced them. No arguments uses the runner sample; test the empty slice with its unit test.

Stuck? Open one hint at a time

Hint 1

The empty case has no maximum. Option describes that state without a sentinel number.

Hint 2

A slice iterator's max() returns an Option of a reference. Copy i32 values before or after selecting the maximum.

Optional reference answer and explanation

Open after a real attempt. These answers are stored separately in hands-on/reference.rs and are never copied into the learner workspace. A passing test is evidence for its cases; explain the behavior and add a counterexample.

pub fn maximum(numbers: &[i32]) -> Option<i32> {
    numbers.iter().copied().max()
}

None is a valid absence, not an error message. Some carries the maximum. Callers must handle both states. An all-negative case catches the common but incorrect zero initializer.

5 · Explain

None is a valid absence, not an error message. Some carries the maximum. Callers must handle both states. An all-negative case catches the common but incorrect zero initializer.

Try a counterexample: Test one element, duplicated maximum values, and empty input. Explain the difference between &i32 and i32 here.

Read the corresponding textbook chapter →

Local textbook file in the ZIP: lessons/06-modeling.md

05 · ex05

Return failure as a value

Parse an i32 and reject negative values. Invalid text and overflow return Err. The error message is your choice; do not panic on user input.

1 · Predict

Predict the Ok/Err branch for 0, 42, -1, abc, and 2147483648. Which failures happen during parsing and which after it?

Write the output or error you predict before running. Copy your observations to observations.md; this draft is cleared on reload.

2 · Implement

Implement only this function in src/lib.rs

pub fn parse_nonnegative(_text: &str) -> Result<i32, String> {
    todo!("ex05: parse_nonnegativeを実装する")
}

3 · Run & test

Run these in work/hands-on

cargo run --offline --example practice -- ex05 42
cargo run --offline --example practice -- ex05 -1
cargo run --offline --example practice -- ex05 abc
cargo run --offline --example practice -- ex05 2147483648
cargo test --offline ex05 -- --ignored

4 · Compare

Expected behavior after your implementation

42 → actual = Ok(42)
-1, abc, 2147483648 → actual = Err(...)
0 → Ok(0) (test)
Err text is intentionally unconstrained.

These are the specified expected results, not a claim that your local code has already produced them. No arguments uses the runner sample; test the empty slice with its unit test.

Stuck? Open one hint at a time

Hint 1

Parsing already returns Result. Match it, or convert the error to String with map_err and propagate with ?.

Hint 2

After parsing succeeds, compare the number with zero. Return Err for a negative value and Ok for a nonnegative value. Avoid unwrap().

Optional reference answer and explanation

Open after a real attempt. These answers are stored separately in hands-on/reference.rs and are never copied into the learner workspace. A passing test is evidence for its cases; explain the behavior and add a counterexample.

pub fn parse_nonnegative(text: &str) -> Result<i32, String> {
    let number = text.parse::<i32>().map_err(|error| error.to_string())?;
    if number < 0 {
        Err("expected a nonnegative integer".to_owned())
    } else {
        Ok(number)
    }
}

Result carries either a useful value or a failure reason. ? exits the function early on Err; it does not recover by itself. The runner prints the Result so you can inspect both branches. Program exit policy is a separate caller responsibility.

5 · Explain

Result carries either a useful value or a failure reason. ? exits the function early on Err; it does not recover by itself. The runner prints the Result so you can inspect both branches. Program exit policy is a separate caller responsibility.

Try a counterexample: Add a test for i32::MAX and an invalid numeric string. Explain why a failing business rule can be Err without crashing the process.

Read the corresponding textbook chapter →

Local textbook file in the ZIP: lessons/07-errors.md

Record what actually happened

Keep observations.md in your learner workspace. Record the command, output, toolchain, prediction difference, and your explanation. Your learning state remains unverified until you can run and explain it yourself.

Date / exercise / toolchain:
Prediction:
Changed function:
Command and observed output:
Unexpected result:
Explanation in my own words:
Next counterexample:

Continue to the existing curriculum

Keep the textbook as your reference. Continue with ownership diagnostics, debugging, mini-grep, and then the Trail product stages. Product exercises ex07–ex10 remain separate and unsolved.

01–10 → · 11–30 → · Foundations & debugging →

This guide prepares practice. It does not mark your learning complete.