Azize
Azize

Reputation: 4476

Pass full slice range as parameter

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)
}

Upvotes: 2

Views: 371

Answers (2)

Ravi R
Ravi R

Reputation: 1782

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.

Upvotes: -1

Adrian
Adrian

Reputation: 46413

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.

Upvotes: 3

Related Questions