Start learning free

LESSON 2 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat v2 in Rust: Number Lines (-n) with format!

Practice Read the full explanation

Now build the -n flag of the cat tool, as a new function. It prints every line preceded by its 1-based line number, right-aligned in 6 columns, then a tab character, then the line text. Blank lines are numbered too, and an empty list gives an empty string.

Function signature:

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

Format per line: the line number right-aligned in a field 6 characters wide (padded with spaces on the left), then a literal tab (\t), then the original line.

Example:

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

Output:
"     1\thello\n     2\tworld\n     3\tfoo"

When printed:
     1	hello
     2	world
     3	foo

Build the result in a mutable String. Loop over 0..lines.len(), add a "\n" before every line except the first, then add the formatted line.

format!("{:6}\t{}", i + 1, lines[i]) formats one entry; {:6} right-aligns a number in a field 6 characters wide.

The full solution:
impl Solution {
    fn numbered_cat(lines: Vec<String>) -> String {
        let mut result = String::new();
        for i in 0..lines.len() {
            if i > 0 {
                result += "\n";
            }
            result += &format!("{:6}\t{}", i + 1, lines[i]);
        }
        return result;
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Cat V2 in Rust, explained

    Problem overview

    Version 2 of the cat project adds the -n flag as a new function, numbered_cat(lines: Vec<String>) -> String. Each line is printed with its 1-based line number, right-aligned in a field 6 characters wide, then a tab, then the line text. Blank lines are numbered too, and an empty list gives an empty string.

    For ["hello", "world", "foo"] the result is " 1\thello\n 2\tworld\n 3\tfoo". Printed, it looks like this:

         1	hello
         2	world
         3	foo
    

    Version 1 joined plain lines with newlines. This version keeps that structure and changes what each row contains.

    Approach: the same loop, a formatted row

    Each row is built from three parts: the number padded to 6 columns, a tab character, and the original text. Rust's format! macro assembles all three in one expression from a pattern. The separator rule from the previous version stays: a newline goes before every row except the first, so the output never ends with a newline.

    Step by step

    1. Accumulator. let mut result = String::new();, which grows row by row.
    2. Loop by position. for i in 0..lines.len(). The position is needed twice: to number the row, and to pick the line.
    3. Separator. if i > 0, append "\n".
    4. The row. format!("{:6}\t{}", i + 1, lines[i]) builds it. The first placeholder, {:6}, takes i + 1 padded to a width of 6. The number is i + 1 because positions start at 0 and line numbers start at 1. The \t in the pattern is a real tab. The second placeholder, {}, takes the line. The & in front of format!(...) lends the new string to +=.
    5. Return result after the loop.

    The solution in Rust

    impl Solution {
        fn numbered_cat(lines: Vec<String>) -> String {
            let mut result = String::new();
            for i in 0..lines.len() {
                if i > 0 {
                    result += "\n";
                }
                result += &format!("{:6}\t{}", i + 1, lines[i]);
            }
            return result;
        }
    }
    

    About the format pattern: a width such as {:6} pads with spaces up to that many characters, and for numbers the default alignment is to the right. That is exactly the "right-aligned in 6 columns" the task wants, with no extra flag. Text behaves differently: format!("{:6}|", "ab") gives "ab |", left-aligned, so the same width on a string would not produce this layout. A number wider than 6 digits is not cut: line 1,000,000 would simply take 7 characters.

    The type of i + 1 is usize, the type of the range 0..lines.len(). It formats like any integer.

    The tab matters for the format. A tab is one character, but a terminal shows it as a jump to the next tab stop, which is why the printed rows line up even when the lines have different lengths. The number field is a fixed 6 characters wide, so the tab always lands after the same column and the text starts in the same place on every row.

    The function walks the list once and builds each row in time proportional to its length, so the total work grows with the combined size of the lines.

    Edge cases and common mistakes

    • Numbering from 0. Using i instead of i + 1 makes the first row 0.
    • Blank lines. They still get a number and a tab: ["a", "", "b"] gives " 1\ta\n 2\t\n 3\tb", where the middle row is a number, a tab and nothing.
    • Trailing newline. Appending "\n" after each row would add an extra one at the end. The i > 0 check puts it before rows instead.
    • Empty list. The loop doesn't run and the result is "".
    • Wider numbers. At line 10 the padding shrinks to four spaces: the tenth row of a ten-line input is " 10\tl9" when the line text is l9.

    Testing

    ["hello", "world", "foo"]  ->  "     1\thello\n     2\tworld\n     3\tfoo"
    ["a", "", "b"]             ->  "     1\ta\n     2\t\n     3\tb"
    []                         ->  ""
    
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free