Start learning free

LESSON 4 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat v4 in Rust: Concatenate Several Files

Practice Read the full explanation

The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.

A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.

Function signature:

fn concat_cat(all_lines: Vec<Vec<String>>) -> String

Example:

Input: allLines = [["hello", "world"], ["foo", "bar", "baz"]]

Output: "hello\nworld\nfoo\nbar\nbaz"

When printed:
hello
world
foo
bar
baz

Collect every line into a flat Vec<String> with a nested loop, preserving order. Then join the pieces with "\n".

A Vec<String> has a built-in join, so once the lines are flattened you can stitch them together directly:
let mut flat: Vec<String> = Vec::new();
for file_lines in all_lines {
    for line in file_lines {
        flat.push(line);
    }
}
flat.join("\n")


The full solution:
impl Solution {
    fn concat_cat(all_lines: Vec<Vec<String>>) -> String {
        let mut flat: Vec<String> = Vec::new();
        for file_lines in all_lines {
            for line in file_lines {
                flat.push(line);
            }
        }
        flat.join("\n")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Cat V4 in Rust, explained

    Problem overview

    The real cat takes several files and prints them one after another. Version 4 models that with concat_cat(all_lines: Vec<Vec<String>>) -> String. Each inner vector is one "file" of lines. The function flattens all lines in order and joins them with newlines.

    For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz". A file can be empty and adds no lines. If there are no files at all, the result is the empty string.

    Approach: flatten first, then join

    Earlier versions built a string while looping and used i > 0 to decide where newlines go. Here the lines come from nested loops, so there is no single position to test. A simpler plan is to split the work in two. First, collect every line into one flat Vec<String>. Second, join that vector with "\n". The standard library's join puts the separator between elements only, which is the "between, not after" rule the earlier loops implemented by hand.

    Step by step

    1. The flat list. let mut flat: Vec<String> = Vec::new(); starts empty. The type annotation is written out, though Rust could also infer it from the later push.
    2. Outer loop over the files. for file_lines in all_lines. Each file_lines is a Vec<String>.
    3. Inner loop over its lines. for line in file_lines. An empty file never enters this loop, so it adds nothing, with no special case.
    4. Collect. flat.push(line); adds the line at the end, keeping the order: files in order, lines in order within each file.
    5. Join. After both loops, flat.join("\n") is the result. With no semicolon, it is what the function returns.

    The solution in Rust

    impl Solution {
        fn concat_cat(all_lines: Vec<Vec<String>>) -> String {
            let mut flat: Vec<String> = Vec::new();
            for file_lines in all_lines {
                for line in file_lines {
                    flat.push(line);
                }
            }
            flat.join("\n")
        }
    }
    

    Ownership is the Rust detail here. Looping with for file_lines in all_lines consumes the outer vector: each inner vector is moved into file_lines, and each string is moved out of it into line and then into flat. No strings are copied, and all_lines can't be used after the loop, which is fine because the function doesn't need it again. The final join is the one place where the text is copied into a single new String.

    Joining a Vec<String> with a &str separator returns a String, matching the declared return type. Each line is touched once, so the time is proportional to the total size of the input, and flat holds the same lines again, so the extra space is proportional to the number of lines.

    Edge cases and common mistakes

    • Empty files in the middle. [["a"], [], ["b"]] gives "a\nb": no blank line appears for the empty file.
    • Blank lines are real lines. [["a", ""], ["", "b"]] gives "a\n\n\nb", because two empty strings sit between a and b and they produce three newlines.
    • All files empty, or no files. [[], []] and [] both give "".
    • Joining each file separately. Calling join per file and gluing the results would need extra care at the file boundaries, and an empty file would leave a stray separator. Flattening first avoids both.
    • Using a vector after moving it. Code that tries to read all_lines after the loop is a compile error, since the loop took ownership.

    Testing

    [["hello", "world"], ["foo", "bar", "baz"]]  ->  "hello\nworld\nfoo\nbar\nbaz"
    [["a"], [], ["b"]]                            ->  "a\nb"
    [["a", ""], ["", "b"]]                        ->  "a\n\n\nb"
    [[], []]                                      ->  ""
    []                                            ->  ""
    
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free