"Go" Go language learning note five

Source: Internet
Author: User
Tags closure

Function

1, the basic composition of the function

Keyword func, function name, argument list, return value, function body, return statement.

2. Definition of function

Give me a chestnut.

Package MyMath Import "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 in the argument list are the same, such as A and B in the example above, you can omit the type declaration of the preceding variable in the argument list, as follows:

Func Add (A, B int) (ret int, err error) {//...}

If several adjacent return value types in the return value list are the same, they can be combined as above

If there is only one return value, you can write this

  

Func Add (A, b int) int{    //...}

3. Invocation of function

function is very convenient to call, as long as the function of the package is introduced in advance, you can directly call the function in the following way

Import "MyMath"; c: = MyMath. Add (A, b);

 Note: Functions that begin with a lowercase letter are available only within this package, and the functions that begin with uppercase letters can be used by other packages, as well as types and variables. 

4. Indefinite parameters

A, indefinite parameter type

The indefinite parameter refers to the number of parameters passed in an indefinite number, to do this, the first thing to do is to define the function to accept the type of indefinite parameter:

Func myfunc (args ... int) int {for _,arg: = Range args {
Fmt. PRINTLN (ARG)
}
}

Invocation mode

MyFunc (MyFunc) (1,2,3,4,5)

Shaped like ... type format can only exist as a function parameter type, and must be the last parameter. It is a syntactic sugar (syntactic sugar), meaning that this syntax has no effect on the functionality of the language, but is more convenient for programmers to use. In general, the use of syntactic sugars can increase the readability of the program, thus reducing the chance of program errors.

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.

b, the transfer of indefinite parameters

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

C, any type of indefinite parameter

If you want to pass any type, you can define the parameter type as interface{} to see the FMT. PRINTLN's prototype

Func Println (format string, ... interface{}) {//...}

5. Multiple return values

If the caller calls a method with multiple return values, but does not want to care about one of the return values, you can simply use an underscore "_" to skip the return value, such as the following code, which indicates that the caller does not want to care about the error code returned by the function when reading the file:

_,c: = Read ();

6. Anonymous function and Closure

An anonymous function is a way of implementing a function that does not define a function name.

A, anonymous function

In go, functions can be passed like normal variables, similar to C's callback function, but the go language supports defining anonymous functions in code.

Func (A, b int, z float) {  return a*b < int (z)  }

Anonymous functions can be directly assigned to a variable or executed directly:

F: = Func (A, b int) {     return a+b}func (Ch Chan char) {    return ch <-ACK} (Reply_chan)//function directly following the argument list representing the function call

B, closures

An anonymous function is a closed packet.

Closure Basic Concepts:

Closures are blocks of code that can contain free (unbound object-specific) variables that are not defined within the code block or in any global context, but are defined in the context in which the code block is defined. The code block to execute (because free variables are included in the code block, so these free variables and the objects they refer to are not freed) provide a binding computing environment (scope) for free variables.

The value of closures:

The value of a closure is that it can be used as a function object or as an anonymous function, which means, for a type system, not only to represent the data but also to represent the code. Most languages that support closures use functions as first-level objects, meaning that these functions can be stored in variables as arguments to other functions, and most importantly, they can be dynamically created and returned by a function.

Closures in the Go language:

Closures in the Go language also refer to variables outside the function. The closure implementation ensures that as long as the closure is used, the variable referenced by the closure will persist, as shown in the following code:

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 above results are:

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

In the above example, the closure function that the variable a points to refers to the values of the local variables I and j,i are isolated, cannot be modified outside the closure, changes the value of J, and then calls a again, discovering 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, thus guaranteeing the security of I.

 

 

  

 

  

"Go" Go language learning note five

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.