Go language Introduction (iv)--Indeterminate parameters

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Indeterminate parameter types

An indeterminate parameter is a variable number of arguments passed in by a function.

package  mainimport  ( Span class= "hljs-string" > "FMT" ) /* indeterminate parameter function */  Func  Add (a int , args ... int ) (Result int ) {result + = a for  _, arg: = range  args { Result + = arg} return }func  Main () {FMT. Println (Add (1 ,  2 ,  3 ,  4 ,  5 ,  6 ,  7 ,  8 ,  9 ,  

Args in the code is an array slice and can only be placed in the last face of the parameter.

Transfer of indeterminate parameters

func SetData(args ...intint) {    //不定参数的传递    return Add(1, args...)}func main() {    fmt.Println(SetData(123))//输出7    array := []int{1234}    fmt.Println(Add(1array...))//输出11}

Indefinite parameters of any type

/ * Any type of indeterminate parameter, denoted by interface{} * /funcmyprintf (args ...Interface{}) { for_, arg: =Rangeargs {//Iterative indeterminate parameters        SwitchArg. (type) { Case int: FMT. Println (ARG,"is int") Case string: FMT. Println (ARG,"is string") Case float64: FMT. Println (ARG,"is Float64") Case BOOL: FMT. Println (ARG,"is bool")default: FMT. Println ("Unknown type")        }    }}funcMain () {/* Output: Haha int is string 12.5 is float64 false is bool-12.5 is float64 * /myprintf(,"haha",12.5,false,-12.5)}

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.