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
- Create an empty slice of strings named
flat. It will hold every line of every file. - Loop over the files with
for _, fileLines := range allLines. The position isn't needed, so_discards it. - Loop over the lines of that file with
for _, line := range fileLines. - Append each line to
flatand keep the result:flat = append(flat, line). - 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:
[][]stringis 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.appendreturns the new slice. It may have to allocate a bigger backing array, so the result must be assigned back:flat = append(flat, line). Callingappendand ignoring the return value does nothing useful, and the compiler reports that the result is unused.[]string{}againstnil.[]string{}is an empty, non-nil slice.var flat []stringwould be a nil slice, andappendandstrings.Jointreat both the same way, so either works here.strings.Joinneeds thestringspackage. 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.flatwould stay empty. - Blank lines are lines. A file whose only line is
""is not empty, and it counts as one line. - Importing nothing. Without
stringsimported, the call tostrings.Joindoesn't compile.
