Start learning free

LESSON 1 OF 69 · PROJECTS: COMMAND-LINE TOOLS

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

func cat(lines []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.
result := ""
for i := 0; i < len(lines); i++ {
    if i > 0 {
        result += "\n"
    }
    result += lines[i]
}


The full solution:
func cat(lines []string) string {
    result := ""
    for i := 0; i < len(lines); i++ {
        if i > 0 {
            result += "\n"
        }
        result += lines[i]
    }
    return result
}

STEP 1 OF 5
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Cat V1 in Go, explained

    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

    1. Start with an empty string named result. Everything is appended to it.
    2. Loop over the positions with i from 0 while i < len(lines). The index, not just the value, is needed to recognise the first line.
    3. Add a newline when i > 0, before the line itself.
    4. Append lines[i] with +=.
    5. Return result after 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 form for i := 0; i < len(lines); i++ is the classic counting loop. for _, line := range lines would also work, but then you would need a separate counter to know the first line.
    • := declares and infers the type. result := "" creates a string. Every variable has to be used in Go, and result is returned, so the compiler is satisfied.
    • Strings are immutable. result += "\n" builds a new string and assigns it to result. That is fine for a few lines. Copying grows with the size of the result, so for very large inputs strings.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. len of 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 > 1 or i == 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, and result += '\n' does not compile. Use the double-quoted "\n".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free