Problem overview
This project builds a small version of the Unix cat command, one feature per version. Version 1 is the core job: cat(lines: Vec<String>) -> String takes a list of lines and returns them as one string, with a newline character between neighbours, so that printing the result shows one line per row.
For ["hello", "world", "foo"] the result is "hello\nworld\nfoo". Blank lines are real entries and stay in place: ["a", "", "b"] gives "a\n\nb". An empty list gives the empty string.
Approach: a separator goes between lines, not after them
The tempting version appends "\n" after every line. That leaves a newline at the very end, which the expected output doesn't have. The fix is to think of the newline as a separator: it belongs between two lines, so the first line gets none in front of it. The loop knows whether a line is the first from its position, i, so it adds a newline whenever i > 0.
Step by step
- Create the accumulator.
let mut result = String::new();starts empty. It must bemutbecause every pass grows it. - Loop by position.
for i in 0..lines.len()visits0, 1, ..., len - 1. The range excludes the end, so an empty vector runs the body zero times. - Add the separator. If
i > 0, append a newline before the line. - Add the line.
result += &lines[i];appends the text. The&matters:+=on aStringexpects a borrowed&str, and a barelines[i]would try to move aStringout of the vector, which Rust refuses. - Return. After the loop,
return result;hands the finished string back.
The solution in Rust
fn cat(lines: Vec<String>) -> String {
let mut result = String::new();
for i in 0..lines.len() {
if i > 0 {
result += "\n";
}
result += &lines[i];
}
return result;
}
Two language details here. First, &lines[i] is a &String, and Rust converts it to &str automatically where += needs one. Second, "\n" is a string literal with the type &str, so it appends directly.
The standard library can do the same job in one expression, lines.join("\n"). The lesson's loop shows what join does underneath.
The function takes lines by value, so it owns the vector and the strings in it. The loop only borrows each string to copy its text into result, which is why the vector is still intact for the whole loop. The result is a brand new String; the input lines are not modified.
The loop's cost is one pass over the lines. Each append copies that line's characters, so the total work is proportional to the combined length of the lines.
Edge cases and common mistakes
- Trailing newline. Appending
"\n"after each line puts an extra one at the end. Thei > 0check prevents it. - Blank lines.
["", ""]has two entries, so the result is a single"\n": two empty rows with one separator between them. - Empty list. The loop never runs and
resultstays"". - One line.
["only"]gives"only"with no newline at all. - Missing
&.result += lines[i];is a compile error, because aStringcan't be moved out of a vector by indexing.
Testing
Printing the results with {:?} shows the newline characters:
["hello", "world", "foo"] -> "hello\nworld\nfoo"
["a", "", "b"] -> "a\n\nb"
["", ""] -> "\n"
["only"] -> "only"
[] -> ""
