Go中的切片存储引用

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

Slice storage reference in Go

问题

在Go库源代码中,经常可以看到通过创建一个新的切片存储引用来传递切片,例如:

method(s[:])

与直接传递原始切片相比,这样做有什么好处呢?

method(s)
英文:

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)

答案1

得分: 6

s[:]构造通常只用于创建一个引用现有数组的新切片,而不是用于“传递原始切片”。

如果在stdlib中确实使用了s[:],并且s是一个切片,那么它可能是一个重构遗留下来的。如果您知道这样的地方,请在Go的问题跟踪器上报告。

英文:

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.

答案2

得分: 1

你只会在s是一个数组的情况下看到这样的代码,而且你想将其作为参数传递给一个以切片作为输入的函数。看下面的代码。

package main
func main() {
    x := [...]int{1, 2, 3, 4, 5}
    someFunction(x)   // 类型不匹配错误:期望 [] int,传递了 [5] int
    someFunction(x[:])// 没有错误
}

func someFunction(input []int){
    // 使用 input
}

需要注意的是,[] int 和 [5] int 是完全不同的类型。

英文:

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.

huangapple
  • 本文由 发表于 2012年12月5日 04:45:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/13711575.html
匿名

发表评论

匿名网友

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

确定