Slices and iterators · Coding Class
This topic is not available in the selected language or version. Showing the start of this section.
Apply the chapter in three steps: an exercise, a program project, and a debugging task. Implement first, then consult the hints and completion criteria. Use a separate file or working directory for each task.
1. Exercise · Compare pipeline order
Section titled “1. Exercise · Compare pipeline order”Use doubled and over_two from the chapter on [1, 2, 3]. Compare map-then-filter with filter-then-map.
Completion: The first order yields 4, 6; the reverse yields 6. Explain which values the callback sees.
Hint: Filter sees values produced by the preceding stage.
2. Build a program · Consume owned boxes
Section titled “2. Build a program · Consume owned boxes”Use into_iter on [box(10), box(20), box(30)], extracting values with into_inner and summing them. Explain why iter and get cannot consume them in the same way.
Completion: The total is 60; do not reuse the original vector after iteration.
Hint: Box is move-only; into_iter takes ownership of the vector.
3. Debug · Fix view lifetime ordering
Section titled “3. Debug · Fix view lifetime ordering”Fix the code below by reordering statements without copying the slice into a new Vec.
Start with this deliberately broken program.
fn main() { let mut values = [1, 2]; let view = values.as_slice(); values.push(3); println(view.get(0));}xen check class_view.xenDiagnostic excerpt:
cannot mutate 'values' while it is borrowedCompletion: Read 1 through the view, then append 3; checking succeeds.
Hint: Place the view’s last use before changing its source.
Verify and record
Section titled “Verify and record”Use xen check file.xen followed by xen run file.xen for ordinary programs; use xen test file.xen for test-only files. Record the original error, its cause, and the corrected result, then rerun every input in the completion criteria.