Box and recursive data · 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 · Represent the end of a link
Section titled “1. Exercise · Represent the end of a link”Use prepend from the chapter to connect 5, 10, 20 with total 35. Also run the sum for an empty list.
Completion: Totals are 35 and 0; sketch each next link and the final None.
Hint: Create 20 first, then prepend 10 and 5.
2. Build a program · Build a consuming length function
Section titled “2. Build a program · Build a consuming length function”Write length using the same ownership transfer pattern as sum. Construct separate empty and three-node lists to pass to it.
Completion: Results are 0 and 3; do not pass a list to length after consuming it with sum.
Hint: Some contributes 1 plus the tail length; None contributes 0.
3. Debug · Fix reuse of a moved owner
Section titled “3. Debug · Fix reuse of a moved owner”The program renames a box, then consumes it through the old name. Fix the owner used without creating a duplicate box.
Start with this deliberately broken program.
fn main() { let original = box(42); let transferred = original; println(original.into_inner());}xen check class_move.xenDiagnostic excerpt:
value moved hereCompletion: 42 prints once; identify the assignment transferring ownership.
Hint: The new owner is transferred; into_inner also consumes the box.
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.