Strings and collections · 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 · Distinguish bytes and empty items
Section titled “1. Exercise · Distinguish bytes and empty items”Print "한".len() and the length after splitting " red green\tblue " on ASCII whitespace.
Completion: Both results are 3: bytes in the first case, words in the second.
Hint: std.string.split_ascii_whitespace does not produce empty words.
2. Build a program · Build a score summary
Section titled “2. Build a program · Build a score summary”Write a function accepting Vec<Int> that prints the count and total for [10, 20, 30]. Also call it with an empty vector. Iterate over indices without iterators.
Completion: The first call reports count 3 and total 60; empty input reports 0 and 0.
Hint: A 0..values.len() loop also handles empty input.
3. Debug · Fix empty-vector access
Section titled “3. Debug · Fix empty-vector access”The code below checks successfully but fails at runtime. Print empty for an empty vector, otherwise print the first element.
Start with this deliberately broken program.
fn main() { let values: Vec<Int> = []; println(values.get(0));}xen run class_empty.xenDiagnostic excerpt:
vector index out of boundsCompletion: [] prints empty, [7] prints 7, and both exit successfully.
Hint: get() does not return Option. Check length before calling it.
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.