Start learning free

LESSON 363 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v1 — Print Lines in Go

Practice

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

    Cat V1 in Go

    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free