Copies, moves, and references · 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 copies and originals
Section titled “1. Exercise · Compare copies and originals”Run append_copy and append_shared from the chapter, printing the vector before and after each call. Identify which operation preserves or changes the original.
Completion: The original is [1, 2] after changing a copy and [1, 2, 3] after changing through a reference.
Hint: Passing Vec<Int> by value uses an independent copy.
2. Build a program · Build an in-place update
Section titled “2. Build a program · Build an in-place update”Write append_marker(values: &mut Vec<Int>, marker: Int) to append to the original. Add 7 to an empty vector, then 9 to the result.
Completion: The original becomes [7, 9]. Enable explc in the function and caller; make the owner in main mutable.
Hint: Call push through the parameter and pass &mut from the caller.
3. Debug · Fix mutation during a borrow
Section titled “3. Debug · Fix mutation during a borrow”Fix the code below by reordering statements without creating a copy. Identify the reference’s last use.
Start with this deliberately broken program.
#![explc]fn main() { let mut value = 1; let shared = &value; value = 2; println(*shared);}xen check class_borrow.xenDiagnostic excerpt:
while it is borrowedCompletion: Read 1 through the reference, then change the original to 2; checking succeeds.
Hint: Move println(*shared) before the assignment.
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.