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

How to write golang variable length parameters

(*-*)浩
Release: 2019-12-17 11:59:01
Original
3156 people have browsed it

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 
}
Copy after login

Then when calling the function , There are many ways

func main(){
    sum(1, 2)˜
    sum(1, 2, 3)
}
Copy after login

But if I have such parameters now, how should I pass them in

nums := []int{1, 2, 3}
Copy after login

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...)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template