Pass full slice range as parameter

爱⌒轻易说出口 提交于 2021-02-05 07:40:32

问题


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:


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:


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.



来源:https://stackoverflow.com/questions/45486817/pass-full-slice-range-as-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!