What does “…” mean when next to a parameter in a go function declaration?

后端 未结 3 1820
旧巷少年郎
旧巷少年郎 2020-12-09 09:17

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 ...inte         


        
相关标签:
3条回答
  • 2020-12-09 09:39

    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.

    0 讨论(0)
  • 2020-12-09 09:49

    They are variadic functions. They accept a variable number of arguments.

    • Wikipedia: Variadic Functions
    • Go By Example: Variadic Functions
    0 讨论(0)
  • 2020-12-09 09:56

    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.

    0 讨论(0)
提交回复
热议问题