Getting Started with Go language basics--functions

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

Function

The Go language basics comes from "Go language Programming", personal records, and deeper understanding.

function Declaration
The basic composition of the function is: the keyword func, the function name, the argument list, the return value, the function body, and the return statement.

General: Func function name (incoming parameter) (return parameter) {function Body}
Such as:
Package Mymathimport "Errors" func Add (a int, b int) (ret int, err error) {if a < 0 | | b < 0 {//Suppose this function only supports addition of two nonnegative numbers err= errors. New ("should be non-negative numbers!")  return} return a + B, nil//support multiple return values}

If several adjacent parameter types are the same in the parameter list, you can omit the type declaration of the preceding variable, such as:
Func Add (A, B int</span>) (ret int, err error) {//...}
If more than one return value in the return value list is of the same type, it can be combined in the same way.
If the function has only one return value, you can also write this:
Func Add (A, b int) int {//...}

function Call
1. Import the package containing the function
2, the following call
Import "MyMath"//Assume that add is placed in a package called MyMath//... c: = MyMath. ADD (1, 2)

It is important to note that if you want to call the package function externally, the function name you call must be capitalized.
The Go language has this rule: functions that begin with a lowercase letter are visible only within this package, and functions that begin with uppercase letters can be used by other packages.
This rule also applies to the visibility of types and variables.

Indeterminate parameters

An indeterminate parameter is a variable number of arguments passed in by a function. To do this, you first need to define the function to accept the indeterminate parameter type:
Func myfunc (args ... int) {//Parameter name ... type for _, arg: = Range args {fmt. Println (ARG)}}
The function can receive an indefinite number of parameters, such as:
MyFunc (2, 3, 4) MyFunc (1, 3, 7, 13)

From the internal implementation mechanism, the type ... type is essentially an array slice, that is, []type, which is why the above parameter, args, can use a for loop to get each incoming parameter.
If there is no such grammatical sugar as the type, the developer will have to write:

Func myfunc2 (args [] int) {For _, arg: = Range args {fmt. Println (ARG)}}
From the point of view of the function implementation, this has no effect, how to write it. But from calling Towners, the situation is completely different:

MYFUNC2 ([] int{1, 3, 7, 13})
You will find that we have to add []int{} to construct an array tile instance.

Transfer of indeterminate parameters
Func myfunc (args ... int) {//pass MYFUNC3 as-is (args ...) Passing fragments, virtually any int slice can be passed in myfunc3 (args[1:] ...)}

Indefinite parameters of any type

The previous example constrains the indeterminate parameter type to int, and if you want to pass any type, you can specify a type of interface{}.
Here is the fmt,printf () function prototype in the Go language:
Func Printf (format string, args ... interface{}) {//...}
The following code allows us to clearly know the type of incoming parameters:
Package Mainimport "FMT" func myprintf (args ... interface{}) {for _, arg: = range args {switch arg. (type) {case  int : FMT. Println (ARG, "is a int value.") Case string:fmt. Println (ARG, "is a string value.") Case int64:fmt. Println (ARG, "is an Int64 value.") default:fmt. Println (ARG, "is an unknown type.")} }}func Main () {var V1 int = 1 var v2 int64 = 234 var v3 string = "Hello" var v4 float32 = 1.234 myprintf (v1, v2, v3, v4)}

The output of this program is:
1 is an int value.234 are an int64 Value.hello are a string value.1.234 is an unknown type.

anonymous functions and closures
In go, a function can be passed or used like a normal variable, which is similar to the C-language callback function. Different
Is that the Go language support defines anonymous functions in the code at any time.
An anonymous function consists of a function declaration and a function body without a function name, as follows:
Func (A, b int, z float64) bool {return a*b <int (z)}

Anonymous functions can be directly assigned to a variable or executed directly:
F: = func (x, y int) int {return x + y}func (ch chan int) {ch <-ACK} (Reply_chan)//curly brace directly followed by argument list representing function call

Closed Package
Closures are blocks of code that can contain variables that are free (not bound to specific objects) that are not within this block of code or
Defined in any global context, but in the context in which the code block is defined. The code block to execute (because the free variable contains
In the code block, so these free variables and the objects they refer to are not freed) to provide a binding calculation ring for the free variable
Environment (SCOPE).

This is the official statement, my understanding is: Simply say a closed func, it can access its externally declared variables, but external access to its internal declaration of variables, unless it is willing to provide a handle

Closures in the Go language also refer to variables outside the function. Closures are implemented to ensure that as long as closures are used,
Variables referenced by closures will always exist, such as:
Package Mainimport ("FMT") func main () {var J int = 5 A: = Func () (func ()) {var i int = ten return func () {fmt. Printf ("I, J:%d,%d\n", I, J)}} () A () J *= 2 A ()}

The result of the above example is:

I, J:10, 5i, J:10, 10

In the above example, the closure function that the variable a points to refers to the local variables I and J, the value of I is isolated, and the outside of the closure does not
Can be modified, after changing the value of J, call a again to find that the result is a modified value.
In the closure function that the variable a points to, only the internal anonymous function can access the variable I and cannot be accessed by other means
To ensure the safety of I.
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.