Start learning free

LESSON 6 OF 69 · PROJECTS: COMMAND-LINE TOOLS

head v2 in Go: The First n Lines with a Loop

Practice Read the full explanation

Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ len(lines). If n is 0 the result is the empty string.

Function signature:

func head(lines []string, n int) string

Example:

Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Loop with i from 0 to n - 1, accumulating each line into a string. Insert a "\n" before every line except the first.

for i := 0; i < n; i++ {
    if i > 0 {
        result += "\n"
    }
    result += lines[i]
}


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

STEP 1 OF 6
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Head V2 in Go, explained

    Problem overview

    Version 2 of the head tool takes a count: head(lines []string, n int) string returns the first n lines joined by newline characters. For this version n is assumed to satisfy 0 <= n <= len(lines). If n is 0, the result is the empty string.

    For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3 the result is "alpha\nbeta\ngamma". The previous version always kept 10 lines; now the count comes from the caller.

    Approach: build the string line by line

    This version builds the result with a loop that runs n times. In each pass, it adds a newline first, unless this is the first line, and then the line itself. Putting the separator before each line except the first gives newlines between lines and none at the end.

    Because the assumption is that n never exceeds the number of lines, the loop can use lines[i] for every i below n without any clamping.

    Step by step

    1. Start with an empty result.
    2. Loop with i from 0 while i < n. The index runs from 0 to n - 1, so exactly n lines are visited.
    3. Add a newline when i > 0, which is every pass except the first.
    4. Append lines[i] to result.
    5. Return result. For n = 0 the loop never runs, so it is still the empty string.

    The solution in Go

    func head(lines []string, n int) string {
    	result := ""
    	for i := 0; i < n; i++ {
    		if i > 0 {
    			result += "\n"
    		}
    		result += lines[i]
    	}
    	return result
    }
    

    The Go details:

    • Indexing is checked. Go doesn't read outside a slice. If n is larger than len(lines), the loop panics with index out of range when i reaches the length. With five lines and n = 6, the message is index out of range [5] with length 5. That is why this version states its assumption.
    • Negative n doesn't fail. The condition i < n is false at once, so the loop is skipped and the result is "". This lesson doesn't promise anything for negative values.
    • Strings are immutable. Each += makes a new string. For a few lines this is fine.
    • The loop variable. i is declared in the for statement and exists only inside it.

    Tracing

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

    n = 3  ->  "alpha\nbeta\ngamma"
    n = 0  ->  ""
    n = 5  ->  "alpha\nbeta\ngamma\ndelta\nepsilon"
    

    The slicing alternative

    Because the lines already sit in a slice, the same result can come from slicing and joining, as in strings.Join(lines[:n], "\n"). For any n from 0 up to len(lines) it returns the same string as the loop: lines[:0] is empty and joins to "", and lines[:len(lines)] is the whole slice. The loop version is worth writing here because it shows the separator rule in action. It also copies the growing string on every +=, so for large inputs joining is cheaper, since it builds the result in one pass.

    Edge cases and common mistakes

    • n = 0. The empty string comes back, and nothing is indexed.
    • n equal to the length. All lines are returned, and the last valid index is n - 1.
    • Using i <= n. The loop would visit n + 1 lines and panic when n equals the length.
    • The separator test. Testing i > 0 puts a newline before every line except the first. Testing i < n-1 after the line would also work, but mixing the two styles gives an extra or a missing newline.
    • A trailing newline. The result has none, since the newline is added before a line and never after it.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free