将完整的切片范围作为参数传递

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

Pass full slice range as parameter

问题

考虑下面的代码,我看到有些代码使用这种格式v[:]来传递完整的切片(而不是其中的一部分)作为参数。

v[:]v之间有什么区别吗?还是只是开发者的偏好?

我下面进行的测试显示没有区别。我有什么遗漏吗?

package main

import (
	"fmt"
)

func main() {
	v := []byte {1, 2, 3}

	printSliceInfo(v)
	printSliceInfo(v[:])
}

func printSliceInfo(s []byte) {
	fmt.Printf("Len: %v - Cap: %v - %v\n", len(s), cap(s), s)
}
英文:

Considering the code below, I have seen some code using this format v[:] for pass full slice (not part of it) as parameter.

Is there any difference between v[:] and v? Or it is just a developer preference?

The test I did below show me no difference. Am I missing something?

package main

import (
	"fmt"
)

func main() {
	v := []byte {1, 2, 3}

	printSliceInfo(v)
	printSliceInfo(v[:])
}

func printSliceInfo(s []byte) {
	fmt.Printf("Len: %v - Cap: %v - %v\n", len(s), cap(s), s)
}

答案1

得分: 3

v 是一个切片时,vv[:] 之间没有区别。当 v 是一个数组时,v[:] 是覆盖整个数组的切片。

英文:

When v is a slice, there is no difference between v and v[:]. When v is an array, v[:] is a slice covering the entirety of the array.

答案2

得分: -1

有一个区别。你可能想要阅读Golang规范中的切片表达式

a[:]   // 等同于 a[0 : len(a)]

v[:]实际上是一个新的切片值(也就是说你现在有两个切片 - v 和 v[:]),所以在这样做之前你需要考虑为什么真正需要它。在你稍微了解一下切片之后,这里有一些可能帮助你理解区别的东西:https://play.golang.org/p/cJgfYGS78H

附:你上面定义的v := []byte {1, 2, 3}是一个切片,所以数组在这里并不相关。

英文:

There is a difference. You may want to read Slice Expression in the Golang spec

a[:]   // same as a[0 : len(a)]

v[:] is actually a new slice value (that is you then have two slices - v & v[:]), so you need to think why you really need it before doing this. Here's something which may help you understand the difference maybe after you read up a bit on slices: https://play.golang.org/p/cJgfYGS78H

p.s.: What you have defined above v := []byte {1, 2, 3} is a slice, so array is not in picture here.

huangapple
  • 本文由 发表于 2017年8月3日 22:15:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/45486817.html
匿名

发表评论

匿名网友

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

确定