3. Toad notes Go language-functions

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

3. Toad notes Go language-functions

Function

A function can have no arguments or accept multiple arguments.

Add accepts two parameters of type int .

Code

Package Main

Import "FMT"

Func Add (x int, y int) int {

Returnx + y

}

Func Main () {

Fmt. Println (Add (42,13))

}

Execution Result:

55

When two or more consecutive function named arguments are of the same type, they can be omitted except for the last type.

In this case,

x int, y int

Be abbreviated as

x, y int

Multi-value return

The function can return any number of return values.

The swap function returns two strings.

For example:

Package Main

Import "FMT"

Func swap (x, y String) (string, string) {

Returny, X

}

Func Main () {

A, B: =swap ("Hello", "World")

Fmt. Println (A, B)

}

Perform:

World Hello

Named return value

The return value of Go can be named and used as a variable.

The name of the return value should have some meaning and can be used as a document.

A return statement with no arguments returns the current value of the result. Which means ' direct ' return.

The direct return statement should only be used in short functions such as the following. In long functions, they can affect the readability of the code.

The code is as follows:

Package Main

Import "FMT"

Func split (sum int) (x, y int) {

x = sum* 4/9

y = sum-x

Return

}

Func Main () {

Fmt. Println (Split (17))

}

Execution Result:

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.