Start learning free

LESSON 4 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat v4 in Go: Concatenating 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:

func concatCat(allLines [][]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 []string with a nested loop, preserving order. Then join the pieces with "\n".

The strings package provides strings.Join, so once the lines are flattened you can stitch them together directly:
flat := []string{}
for _, fileLines := range allLines {
    for _, line := range fileLines {
        flat = append(flat, line)
    }
}
return strings.Join(flat, "\n")


The full solution:
func concatCat(allLines [][]string) string {
    flat := []string{}
    for _, fileLines := range allLines {
        for _, line := range fileLines {
            flat = append(flat, line)
        }
    }
    return strings.Join(flat, "\n")
}

STEP 1 OF 5
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Cat V4 in Go, explained

    Problem overview

    Version 4 mirrors what the real cat does with several file arguments: it prints them one after another. The function concatCat(allLines [][]string) string receives a slice of "files", where each file is itself a slice of lines. It flattens all the 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, and with no files at all the result is the empty string. The first version of the tool joined one list of lines; this one first merges many lists into one.

    Approach: flatten, then join once

    Instead of tracking separators across file boundaries, collect every line into one flat slice and join once at the end. This avoids the problem of deciding whether a newline belongs between files, because after flattening there are no files, only lines. An empty file contributes nothing to the flat slice, so no extra newline appears for it.

    Step by step

    1. Create an empty slice of strings named flat. It will hold every line of every file.
    2. Loop over the files with for _, fileLines := range allLines. The position isn't needed, so _ discards it.
    3. Loop over the lines of that file with for _, line := range fileLines.
    4. Append each line to flat and keep the result: flat = append(flat, line).
    5. Join the result after both loops with strings.Join(flat, "\n").

    The solution in Go

    func concatCat(allLines [][]string) string {
        flat := []string{}
        for _, fileLines := range allLines {
            for _, line := range fileLines {
                flat = append(flat, line)
            }
        }
        return strings.Join(flat, "\n")
    }
    

    The Go details:

    • [][]string is a slice of slices. The outer slice has one element per file, and each element is a []string. The inner slices can have different lengths.
    • append returns the new slice. It may have to allocate a bigger backing array, so the result must be assigned back: flat = append(flat, line). Calling append and ignoring the return value does nothing useful, and the compiler reports that the result is unused.
    • []string{} against nil. []string{} is an empty, non-nil slice. var flat []string would be a nil slice, and append and strings.Join treat both the same way, so either works here.
    • strings.Join needs the strings package. It takes a slice and a separator, puts the separator between items only, and returns the empty string for an empty slice.
    • The three dots as a shortcut. flat = append(flat, fileLines...) would add a whole file at once. The lesson's inner loop does the same thing one line at a time.

    Tracing

    These inputs and results come from running the function (shown as Go string literals):

    concatCat([["hello", "world"], ["foo", "bar", "baz"]])  ->  "hello\nworld\nfoo\nbar\nbaz"
    concatCat([["a"], [], ["b"]])                           ->  "a\nb"
    concatCat([[], []])                                     ->  ""
    concatCat(nil)                                          ->  ""
    concatCat([[""], [""]])                                 ->  "\n"
    

    The empty file in the second row adds nothing, and the result has no doubled newline. The last row is different: each file holds one blank line, so there are two lines, both empty, and the output is one newline between them.

    Edge cases and common mistakes

    • Joining each file and then joining again. An empty file would give an empty string, and the second join would put a newline around it, creating a blank line that isn't in the input.
    • Forgetting to assign append's result. flat would stay empty.
    • Blank lines are lines. A file whose only line is "" is not empty, and it counts as one line.
    • Importing nothing. Without strings imported, the call to strings.Join doesn't compile.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free