Start learning free

LESSON 376 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v4 — Concatenate Multiple Files in Rust

Practice

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

    Cat V4 in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free