In many languages, variable parameters, function overloading, and closure in functional languages are provided to improve the flexibility of functions. If you have used the functions in the FMT package, you have reached the indefinite parameters of golang. So how can we define a function with variable parameters?
I. Function Definition
First, let's take a look at how to define a function with an indefinite parameter:
func YourFun(v... interface{}){}
This function defines a function that accepts any number of parameters of any type. The special syntax here is as follows: ", after adding three vertices to a variable, it indicates that the variable is accepted from this place. Different from Python, if golang's indefinite parameters Replace "interface {}" with a definite type, they can only accept the indefinite parameters of this type.
2. Three points
As shown above, there are three special marks. So what are the functions of these three points?
2.1 indefinite Parameters
As mentioned above, when an indefinite parameter is defined, it indicates that an indefinite parameter is recorded from this parameter.
2.2 dereference slice
When you want to pass several values to an indefinite parameter function, you can manually write each parameter or pass an slice to the function:
YourFunc (YourSlice...)
You can pass the corresponding parameters in the slice to the function through. Equivalent to "* ARGs" in Python"
It should be noted that currently, slice can only be used when parameters are passed through an indefinite parameter function. If it is used elsewhere, an error is reported.
Iii. traversal Parameters
Let's look at an example:
func P (v... string) {for _,item := range v { fmt.Println("item:",item) }}func main() { var l []string l = append(l,"a") l = append(l,"b") fmt.Println("l is ",l) P(l...)}
Here we can see that a complete list is first followed by each element:
l is [a b]item: aitem: b
You can use for... range to traverse each parameter in variable v. Here, we set the variable parameter type to string, so we can only accept several parameters of the string type.
Variable parameters of golang