Variadic function

A variadic function is a function that accepts an unlimited number of parameters. Generally, they are expressed in the following form

func hello(friends ...string) {
    // ...
}

It is easy to identify from three points....

We can callhello()like this:

hello("tony", "mark", "mary", "joe")

or:

hello("tony")

Or use an unlimited number of strings.

Example from the standard library:append()

appendIs a variable function, defined as

func append(slice []Type, elems ...Type) []Type

A common usage is when removing items from a locationiFrom the arraya.

a = append(a[:i], a[i+1:]...)

This line creates a new slice by removing the item at the positioniina, The method is to combine items from 0 to i (not included) and from i + 1 to the end.

What is the purpose...?

appendAccept slice as the first parameter, and accept an unlimited number of parameters, all parameters have typesAssignableThe type of its element.

writing

a = append(a[:i], a[i+1:]...)

Equivalent to 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.

usea[i+1:]...Basically a shorthand syntax, as described in the Go specificationhttps://golang.org/ref/spec#Passing_arguments_to_..._parameters:

If f is a variable parameter whose final parameter p is of type...T, then the type of p within f is equivalent to the type [] T. If f is called without the actual parameter of p, the value passed to p is nil. Otherwise, the passed value is a new slice of type [] T, with a new base array, and its continuous elements are actual parameters, all of which must be assignable to T

playground


More tutorials: