英文:
What does "..." mean when next to a parameter in a go function declaration?
问题
我正在查看一些用Google的Go语言编写的代码,然后我遇到了这个:
func Statusln(a ...interface{})
func Statusf(format string, a ...interface{})
我不明白...
是什么意思。有人知道吗?
英文:
I was going through some code written in Google's Go language, and I came across this:
func Statusln(a ...interface{})
func Statusf(format string, a ...interface{})
I don't understand what the ...
means. Does anybody know?
答案1
得分: 32
这意味着你可以使用可变数量的参数调用Statusln函数。例如,使用以下方式调用该函数:
Statusln("hello", "world", 42)
将会给参数a赋予以下值:
a := []interface{}{"hello", "world", 42}
因此,你可以遍历这个切片a并处理所有参数,无论有多少个参数。一个常见且流行的可变参数用例是fmt.Printf(),它接受一个格式字符串和可变数量的参数,这些参数将根据格式字符串进行格式化。
英文:
It means that you can call Statusln with a variable number of arguments. For example, calling this function with:
Statusln("hello", "world", 42)
Will assign the parameter a the following value:
a := []interface{}{"hello", "world", 42}
So, you can iterate over this slice a and process all parameters, no matter how many there are. A good and popular use-case for variadic arguments is for example fmt.Printf() which takes a format string and a variable number of arguments which will be formatted according to the format string.
答案2
得分: 7
它们是可变参数函数。这些函数接受可变数量的参数。
示例
下面的sums
函数接受多个整数:
package main
import "fmt"
func sum(nums ...int) {
fmt.Print(nums, " ")
total := 0
for _, num := range nums {
total += num
}
fmt.Println(total)
}
func main() {
sum(1, 2)
sum(1, 2, 3)
nums := []int{1, 2, 3, 4}
sum(nums...)
}
更多信息
英文:
They are variadic functions. These functions accept a variable number of arguments.
Example
The sums
function below accepts multiple integers:
package main
import "fmt"
func sum(nums ...int) {
fmt.Print(nums, " ")
total := 0
for _, num := range nums {
total += num
}
fmt.Println(total)
}
func main() {
sum(1, 2)
sum(1, 2, 3)
nums := []int{1, 2, 3, 4}
sum(nums...)
}
For more info
答案3
得分: 6
这是可变长度参数
func Printf(format string, v ...interface{}) (n int, err error) {
以这个签名为例。在这里,我们定义了一个要打印的字符串,但是这个字符串可以与可变数量的东西(任意类型)进行插值替换(实际上,我从fmt包中取出了这个函数):
fmt.Printf("just i: %v", i)
fmt.Printf("i: %v and j: %v",i,j)
正如你在这里看到的,使用可变参数,一个签名适用于所有长度。
此外,您可以指定一些确切的类型,如...int
。
英文:
It is variable length argument
func Printf(format string, v ...interface{}) (n int, err error) {
Take for example this signature. Here we define that we have one string to print, but this string can be interpolated with variable number of things (of arbitrary type) to substitude (actually, I took this function from fmt package):
fmt.Printf("just i: %v", i)
fmt.Printf("i: %v and j: %v",i,j)
As you can see here, with variadic arguments, one signature fits all lengths.
Moreover, you can specify some exact type like ...int
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论