Reputation: 8495
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?
Upvotes: 3
Views: 3571
Reputation: 8425
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.
Upvotes: 10