Home>Article>Backend Development> How to write golang variable length parameters
Generally, the parameters of functions are fixed length, but some parameters can be passed in an indefinite number of parameters. The golang language also has this usage
For example, a function is written like this(recommended learning:go)
func sum(nums ...int){ total := 0 for _, num := range numes{ total += num } return total }
Then when calling the function , There are many ways
func main(){ sum(1, 2)˜ sum(1, 2, 3) }
But if I have such parameters now, how should I pass them in
nums := []int{1, 2, 3}
It’s obvious This is a slice. You can only do it in reverse and pass it into the function
nums := []int{1, 2, 3} sum(nums...)
The above is the detailed content of How to write golang variable length parameters. For more information, please follow other related articles on the PHP Chinese website!