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
}
Could anyone tell me what the three dots are here?
And what does ...interface{}
do?
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:A parameter:
Is, for the function equivalent to:
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:
Will do the same as:
This is explained quite well in the Go Specification as well:
As far as the
interface{}
term, it is the empty interface. In other words, the interface implemented by all variables in Go.This is sort of analogous to
java.lang.object
orsystem.object
in C#, but is instead inclusive of every variable type in the language. So it lets you pass in anything to the method.