Start learning free

LESSON 1 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat v1 in Rust: Print Lines by Joining Strings

Practice Read the full explanation

Build a tiny version of the Unix cat command. Given a list of lines, return them joined by newline characters (\n) so they print one per line.

Lines can be blank, and the list can be empty (the result is then an empty string).

Function signature:

fn cat(lines: Vec<String>) -> String

Example:

Input: lines = ["hello", "world", "foo"]

Output: "hello\nworld\nfoo"

When printed:
hello
world
foo

Build the result manually: walk through the lines in order and accumulate them into a single String, inserting a "\n" between every pair.

A clean trick: only prepend "\n" when i > 0. That way the first line has no separator before it, and every subsequent line is preceded by exactly one newline.
let mut result = String::new();
for i in 0..lines.len() {
    if i > 0 {
        result += "\n";
    }
    result += &lines[i];
}


The full solution:
impl Solution {
    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;
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Cat V1 in Rust, explained

    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

    1. Create the accumulator. let mut result = String::new(); starts empty. It must be mut because every pass grows it.
    2. Loop by position. for i in 0..lines.len() visits 0, 1, ..., len - 1. The range excludes the end, so an empty vector runs the body zero times.
    3. Add the separator. If i > 0, append a newline before the line.
    4. Add the line. result += &lines[i]; appends the text. The & matters: += on a String expects a borrowed &str, and a bare lines[i] would try to move a String out of the vector, which Rust refuses.
    5. 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. The i > 0 check 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 result stays "".
    • One line. ["only"] gives "only" with no newline at all.
    • Missing &. result += lines[i]; is a compile error, because a String can'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"
    []                         ->  ""
    
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free