Reputation:
In the Go library source you often see that a slice is passed by creating a new slice storage reference like so
method(s[:])
What's the benefit of this, compared to just passing the original slice?
method(s)
Upvotes: 5
Views: 213
Reputation: 16023
The only case where you would see code like this is when s is an array, and you want to pass as a parameter to a function that takes a slice as its input. Take the following code.
package main
func main() {
x := [...]int{1, 2, 3, 4, 5}
someFunction(x) // type mismatch error : expecting [] int, passed [5] int
someFunction(x[:])// no error
}
func someFunction(input []int){
// use input
}
The thing to note here is that [] int and [5] int are entirely different types.
Upvotes: 1
Reputation: 91243
The s[:]
construct is normally used only to create a new slice referencing an existing array, not for "passing the original slice".
If s[:]
is really used somewhere in the stdlib and s
is a slice than it could be e.g. a refactoring leftover. Please report such place if known to you on the Go issue tracker.
Upvotes: 6