5. Function Functions

Source: Internet
Author: User

A function can have zero or several parameters.

In the following example, two int-type parameters are added.

Note that this type is behind the variable name.

(For more information about types, seeArticleYou can read this articleArticle on Go's declaration syntax.)

1Package main
2
3Import"FMT"
4
5Func add (xInt, YInt)Int{
6ReturnX + Y
7}
8
9Func main (){
10FMT. println (add (42,13))
11}
 
55

When there are two or more parameters of the same type, we can ignore the previous Type Definitions and leave the last one.

In the following statement, we can scale it down as follows:

 
X int, y int

Change

 
X, Y int
1Package main
2
3Import"FMT"
4
5Func add (X, YInt)Int{
6ReturnX + Y
7}
8
9Func main (){
10FMT. println (add (42,13))
11}
 
55

A function can return any number of values.

The following method returns two.

 1 Package main
2
3 Import " FMT "
4
5 Func swap (X, Y string) (string, string ){
6 Return Y, X
7 }
8
9 Func main (){
10 A, B: = swap ( " Hello " , " World " )
11 FMT. println (A, B)
12 }
 
World Hello

In the go language, you can return not only a single value, but also multiple values.

If the returned value name already declares a variable in the function body, no content is needed after return.

1Package main
2
3 Import "FMT"
4
5Func split (sum INT) (X, y int ){
6X = sum * 4/9
7Y = sum-x
8Return
9}
10
11Func main (){
12FMT. println (split (17 ))
13}
 
7 10

 

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.