Home >Backend Development >Golang >Detailed explanation of indefinite parameters in golang
#Indefinite parameters means that the number of parameters passed in by the function is an indefinite number.
1. Function definition
First let’s look at how to define a function with variable parameters:
func YourFun(v... interface{}){ }
This function definition defines a function that accepts any number of parameters of any type. The special syntax here is three dots "...
". After adding three dots after a variable, it means that indefinite parameters are accepted from that point. Unlike python, if golang's indefinite parameters are Here "interface{}
" is replaced with a certain type, then it can only accept variable parameters of that type.
2. "..."
Above we see the special mark with three dots "...". So what do these three dots "..." do?
2.1 Indefinite parameters
As mentioned above, when defining an indefinite parameter, it means recording the indefinite parameters starting from this parameter
2.2 Dereferencing slice
When When you want to pass several values to a variable parameter function, you can manually write each parameter, or you can pass a slice to the function:
YourFunc (YourSlice...)
You can use "...
" Pass the corresponding parameters in the slice to the function. Equivalent to "*args" in python.
It should be noted here that dereferencing slice can currently only be used when passing parameters in variable parameter functions. If used elsewhere, an error will be reported.
3. 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...) }
The result we see here is, first a complete list, Then each element:
l is [a b] item: a item: b
By using for...range
, you can traverse each parameter in the indefinite parameter v. Here we set the variable parameter type to string, so it can only accept a number of string type parameters.
Recommended related articles and tutorials: golang tutorial
The above is the detailed content of Detailed explanation of indefinite parameters in golang. For more information, please follow other related articles on the PHP Chinese website!