... interface {}(点点接口)的含义 [英] Meaning of ...interface{} (dot dot dot interface)
问题描述
下面是我有疑问的Go代码.
具体来说,此功能中的a
是什么?
Below is a piece of Go code I have question about.
Specifically, what is a
in this function?
func DPrintf(format string, a ...interface{}) (n int, err error) {
if Debug > 0 {
n, err = fmt.Printf(format, a...)
}
return
}
谁能告诉我这三个点是什么?
...interface{}
是做什么的?
Could anyone tell me what the three dots are here?
And what does ...interface{}
do?
推荐答案
以三个点(...)为前缀的参数类型称为 variadic参数.这意味着您可以将任何数字或参数传递给该参数(就像使用fmt.Printf()
一样).该函数将接收参数的参数列表,作为参数声明的类型的切片(在您的情况下为[]interface{}
). 转到规范指出:
A parameter type prefixed with three dots (...) is called a variadic parameter. That means you can pass any number or arguments into that parameter (just like with fmt.Printf()
). The function will receive the list of arguments for the parameter as a slice of the type declared for the parameter ([]interface{}
in your case). The Go Specification states:
函数签名中的最后一个参数可以具有以...为前缀的类型.具有此类参数的函数称为可变参数(variadic),并且可以使用该参数的零个或多个参数来调用.
The final parameter in a function signature may have a type prefixed with .... A function with such a parameter is called variadic and may be invoked with zero or more arguments for that parameter.
一个参数:
a ...interface{}
是,对于等同于以下功能的功能:
Is, for the function equivalent to:
a []interface{}
区别在于如何将参数传递给此类函数.可以通过分别给切片的每个元素或作为单个切片来完成此操作,在这种情况下,您必须在切片值后缀三个点.以下示例将导致相同的调用:
The difference is how you pass the arguments to such a function. It is done either by giving each element of the slice separately, or as a single slice, in which case you will have to suffix the slice-value with the three dots. The following examples will result in the same call:
fmt.Println("First", "Second", "Third")
将执行以下操作:
s := []interface{}{"First", "Second", "Third"}
fmt.Println(s...)
在转到规范中也对此进行了很好的解释:>
This is explained quite well in the Go Specification as well:
给出函数并调用
Given the function and calls
func Greeting(prefix string, who ...string)
Greeting("nobody")
Greeting("hello:", "Joe", "Anna", "Eileen")
在Greeting
之内的
中,who
在第一个调用中将具有值nil
,在第二个调用中将具有[]string{"Joe", "Anna", "Eileen"}
.
within Greeting
, who
will have the value nil
in the first call, and []string{"Joe", "Anna", "Eileen"}
in the second.
如果最终参数可分配给切片类型[]T
,则在参数后跟...
的情况下,可以将其不变地作为...T
参数的值传递.在这种情况下,不会创建新的切片.
If the final argument is assignable to a slice type []T
, it may be passed unchanged as the value for a ...T
parameter if the argument is followed by ...
. In this case no new slice is created.
给出切片s
并调用
s := []string{"James", "Jasmine"}
Greeting("goodbye:", s...)
在Greeting
之内,who
将具有与s
相同的值,并且具有相同的基础数组.
within Greeting
, who
will have the same value as s
with the same underlying array.
这篇关于... interface {}(点点接口)的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!