英文:
What does slice[0:0] do in Go?
问题
blankLines = blankLines[0:0]
是将切片 blankLines
的长度设置为 0,相当于清空切片。这样做的目的是在每次循环开始时重置 blankLines
,以便重新填充新的数据。这并不是在数组前面添加元素的方式,而是通过重新分配切片的长度来实现清空操作。
英文:
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?
答案1
得分: 9
这个切片[0:0]
创建了一个具有相同底层数组但长度为零的切片。它实际上只是在切片上“重置”了len
,以便可以重新使用底层数组。这样做可以避免在每次迭代时创建全新的切片所需的分配操作。
英文:
This slicing [0:0]
creates a slice that has the same backing array, but zero length. All it's really doing 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论