Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does slice[0:0] do in Go?

Tags:

go

I recently saw the following code in a Golang markdown parser:

    blankLines := make([]lineStat, 0, 128)
    isBlank := false
    for { // process blocks separated by blank lines
        _, lines, ok := reader.SkipBlankLines()
        if !ok {
            return
        }
        lineNum, _ := reader.Position()
        if lines != 0 {
            blankLines = blankLines[0:0]
            l := len(pc.OpenedBlocks())
            for i := 0; i < l; i++ {
                blankLines = append(blankLines, lineStat{lineNum - 1, i, lines != 0})
            }
        }

I'm confused as to what blankLines = blankLines[0:0] does. Is this a way to prepend to an array?

like image 997
Roymunson Avatar asked May 19 '26 03:05

Roymunson


1 Answers

This slicing [0:0] creates a slice that has the same backing array, but zero length. All it's really doing in your example is "resetting" the len on the slice so that the underlying array can be re-used. It avoids the allocation that may be required if a completely new slice was created for each iteration.

like image 198
Hymns For Disco Avatar answered May 21 '26 17:05

Hymns For Disco