Go by Example:variadic Functions

Source: Internet
Author: User
Tags variadic

The Variadic function supports any number of incoming parameters. For example: FMT. PRINTLN is a common variable-parameter function.

Package Mainimport "FMT"//This function can use any number of int types as parameter func sum (nums ... int) {    fmt. Print (Nums, "")    total: = 0    for _, num: = range Nums {Total        + = num    }    fmt. Println (total)}func main () {    //Variadic function support is used in a regular manner,    //also supports only one    sum (1, 2)    sum (1, 2, 3)    // If you need an incoming parameter in a slice, like the following    //"func (Slice ...)" Break the slices into the    nums: = []int{1, 2, 3, 4}    sum (Nums ...)}

The output is:

<strong>$ Go run variadic-functions.go </strong>[1 2] 3[1 2 3] 6[1 2 3 4] 10

Another important feature of functions in the go language is the construction of function closures. We will explain in the next section.

Next example: Go by Example:closures.

English original


Go by Example:variadic Functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.