Problem overview
This is the first version of a small command-line tool modelled on the Unix cat command, which prints text one line per row. The function cat receives a slice of strings, one per line, and returns a single string with the lines joined by \n. There is no newline after the last line.
For ["hello", "world", "foo"] the result is "hello\nworld\nfoo", which prints as three rows. Blank lines are kept, and an empty slice gives an empty string. The next version builds on this one.
Approach: a separator between lines, not after them
The result needs a newline between every two lines. Putting one after every line would leave a stray newline at the end, and putting one before every line would add a stray one at the start. The clean rule is to add a newline before every line except the first, and the loop index tells you which one is first: only when i > 0 does a line have a predecessor.
Step by step
- Start with an empty string named
result. Everything is appended to it. - Loop over the positions with
ifrom 0 whilei < len(lines). The index, not just the value, is needed to recognise the first line. - Add a newline when
i > 0, before the line itself. - Append
lines[i]with+=. - Return
resultafter the loop. For an empty slice the loop never runs and the empty string comes back.
The solution in Go
func cat(lines []string) string {
result := ""
for i := 0; i < len(lines); i++ {
if i > 0 {
result += "\n"
}
result += lines[i]
}
return result
}
The Go details:
- Go has only
for. The three-part formfor i := 0; i < len(lines); i++is the classic counting loop.for _, line := range lineswould also work, but then you would need a separate counter to know the first line. :=declares and infers the type.result := ""creates astring. Every variable has to be used in Go, andresultis returned, so the compiler is satisfied.- Strings are immutable.
result += "\n"builds a new string and assigns it toresult. That is fine for a few lines. Copying grows with the size of the result, so for very large inputsstrings.Join(lines, "\n")is the better tool. The lesson writes the loop by hand so the separator logic is visible. - An empty or nil slice is fine.
lenof a nil slice is 0, so the loop is skipped.
Tracing
These inputs and their results come from running the function:
cat(["hello", "world", "foo"]) -> "hello\nworld\nfoo"
cat(["a", "", "b"]) -> "a\n\nb"
cat([""]) -> ""
cat(nil) -> ""
Notice that a slice holding one empty line and an empty slice both give the empty string. The two cases differ in the input but not in this output, because with a single line there is no separator to add.
Edge cases and common mistakes
- A trailing newline. Adding
"\n"after every line makes the result end with a newline, which the lesson's tests don't expect. - Checking
i > 1ori == 1. Either one skips the separator between the first and second lines, so they run together. - Blank lines. They are ordinary entries, so
["a", "", "b"]gives two newlines in a row. Don't skip empty strings. - Using
'\n'in single quotes. In Go that is a rune, not a string, andresult += '\n'does not compile. Use the double-quoted"\n".
