Home  >  Article  >  Backend Development  >  How to write golang variable length parameters

How to write golang variable length parameters

(*-*)浩
(*-*)浩Original
2019-12-17 11:59:013095browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn