Go gotcha: Extra comma in slice literal

Why doesn't this program compile:

func main() {
        fruit := []string{
                "apple",
                "banana",
                "cherry"
        }
        fmt.Println(fruit)
}
../main.go:5:11: syntax error: unexpected newline, expecting comma or }
Answer

In a multi-line slice, array or map literal, every line must end with a comma:

func main() {
        fruit := []string{
                "apple",
                "banana",
                "cherry", // Comma added
        }
        fmt.Println(fruit)
        // Output: [apple banana cherry]
}

This behavior is a consequence of the Go semicolon insertion rules.

This has the effect that adding, removing or reordering lines doesn’t require modification to surrounding lines which makes it easier to make changes and diffs look cleaner.

Comments

Be the first to comment!