可变参数函数模板
Variadic Functions are functions that accept an unlimited number of arguments. Typically, they are expressed in the form
可变参数函数是接受无限数量的参数的函数。 通常,它们以以下形式表示
func hello(friends ...string) {
// ...
}
Very easy to recognize from the 3 dots ...
.
很容易从3点认识...
。
We can call hello()
like this:
我们可以这样调用hello()
:
hello("tony", "mark", "mary", "joe")
or:
要么:
hello("tony")
or with an infinite number of strings.
或无数个字符串。
标准库中的示例: append()
(An example from the standard library: append()
)
append
is a variadic function, defined as
append
是一个可变参数函数,定义为
func append(slice []Type, elems ...Type) []Type
A common usage is when removing an item at position i
from an array a
.
一种常见用法是从数组a
删除位置i
处的项目时。
a = append(a[:i], a[i+1:]...)
This line creates a new slice by removing the item at position i
in a
, by combining the items from 0 to i (not included), and from i+1 to the end.
这条线通过在位置移除所述项目创建一个新的切片i
在a
,由从0的项目组合,以I(不包括在内),和从i + 1到最后。
What is the purpose of ...
?
...
的目的是什么?
append
accepts a slice as first argument, and an unlimited number of arguments, all with a type assignable to the type of its elements.
append
接受一个slice作为第一个参数,并接受无限数量的参数,所有参数的类型都可分配给其元素的类型。
Writing
写作
a = append(a[:i], a[i+1:]...)
is equivalent as writing
相当于写作
a = append(a[:i], a[i+1], a[i+2], a[i+3], a[i+4]) //and so on, until the end of the slice.
Using a[i+1:]...
is basically a shorthand syntax, as the Go spec describes in https://golang.org/ref/spec#Passing_arguments_to_..._parameters:
使用a[i+1:]...
基本上是一种速记语法,如Go规范在https://golang.org/ref/spec#Passing_arguments_to_..._parameters中所述 :
If f is variadic with a final parameter p of type …T, then within f the type of p is equivalent to type []T. If f is invoked with no actual arguments for p, the value passed to p is nil. Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T
如果f是最终参数p为…T类型的可变参数,则在f内p的类型等效于[] T类型。 如果在没有p实际参数的情况下调用f,则传递给p的值为nil。 否则,传递的值是[] T类型的新切片,带有新的基础数组,其后续元素是实际参数,所有这些参数都必须可分配给T
可变参数函数模板