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

huangapple go评论127阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年5月26日 13:54:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/67699224.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定