Some interesting functions of functions in Go

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

Functions in Go

function is the core design of go inside, it is declared by the keyword func, his format is as follows
Func funcname (input1 type1, Input2 type2) (output1 type1, Output2 type2) {
Here is the process logic code
Return multiple values
return value1, value2
}

Functions have the following characteristics:

    • The keyword func is used to declare a function funcname, and an anonymous function can have no funcname.
    • A function can have one or more parameters, followed by a type, passed, delimited
    • function can return multiple values
    • The above return value declares two variables output1 and output2, if you do not want to declare also can, directly on two types
    • If you have only one return value and do not declare a return value variable, you can omit the parentheses that include the return value
    • If there is no return value, then the last return information is omitted directly

function as value, type

function in Go is also a variable, we can define him by type, his type is all have the same parameter, the same return value of a type type_name func (input1 inputType1 [, Input2 inputType2 [, ...]) (Result1 resultType1 [, ...])

What is the benefit of a function as a type? That is, you can pass this type of function as a value, see the example below.

Package Main
Import "FMT"

Type test_int func (int) bool//declares a function type

Func isodd (integer int) bool {
If integer%2 = = 0 {
return False
}
return True
}

Func isEven (integer int) bool {
If integer%2 = = 0 {
return True
}
return False
}

The declared function type is used as a parameter in this place.
Func filter (slice []int, F test_int) []int {
var result []int
For _, Value: = Range Slice {
If f (value) {
result = Append (result, value)
}
}
return result
}

Func Main () {
Slice: = []int {1, 2, 3, 4, 5, 7}
Fmt. Println ("slice =", slice)
Odd: = Filter (slice, isodd)//function as a value to pass
Fmt. Println ("Odd Elements of Slice is:", ODD)
Even: = Filter (slice, isEven)//function as a value to pass
Fmt. Println ("Even elements of Slice is:", even)
}

functions as values and types are very useful when we write some common interfaces, and by the above example we see that the Test_int type is a function type, and then the parameters and return values of the two filter functions are the same as the Test_int type, but we can implement many kinds of logic, This makes our program very flexible.

function return value is a function of the case

Technical Reference: http://www.cnblogs.com/cool-xing/archive/2012/05/19/2509176.html

If you have a list of people who have eaten sushi, can you determine whether he is on the list according to the name of the person? This is a very simple question, you just have to go through the list. Well, what if you're weak in go and don't know how to traverse the list? It doesn't matter, I will provide you with a brush selector:

Func screen (patients []string) func (string) bool {
Defines an anonymous function and returns
return func (name string) bool {
For _, Soul: = Range Patients {
if soul = = name {
return True
}
}
return False
}
}

The screen method returns the selected function to the caller so that you don't have to know how to traverse the list, just call the function that I returned to you to:

A list of people who have eaten sushi.
Those_who_bought_sushi: = []string{"Anand", "JoJo", "Jin", "Mon", "Peter", "Sachin"}
Get the brush selector function
Bought_sushi: = Screen (Those_who_bought_sushi)
Call the brush selector function to know if someone is on the list
Fmt. Println (Bought_sushi ("Anand"))//True
Fmt. Println (Bought_sushi ("Alex"))//False

Closed Package

The earth people know: function is just a piece of executable code, after compiling "cured", each function in memory only one instance, get the function entry point can execute function. A function in the go language can be used as a parameter or return value for another function, and can be assigned to a variable. Functions can be nested defined (using anonymous functions), that is, within one function can define another function, with the structure of nested functions, the closure problem arises. Such as:

Package Main
Import "FMT"

Func exfunc (n int) func () {
Sum:=n
return func () {//assigns the anonymous function as a value to variable a (Go does not allow function nesting.)
However, you can use anonymous functions to implement nested functions)
Fmt. PRINTLN (sum+1)//Call a variable outside this function
}//There is no () anonymous function is not executed immediately
}

Func Main () {
Myfunc:=exfunc (10)
MyFunc ()//11
Myanotherfunc:=exfunc (20)
Myanotherfunc ()//21
MyFunc ()//11
Myanotherfunc ()//21
}

Here the results are executed:

11

21st

11

21st

In this procedure, the anonymous function is an inline function of the function Exfunc and is the return value of the Exfunc function. We notice a problem: The local variable sum,go in the anonymous inline function that is referenced in the outer function will deal with this problem? Let's take a look at the running results of this code first. When we call the function (MyFunc (), Myanotherfunc ()) that is obtained by invoking the Exfunc function by a different parameter, the resulting result is isolated, meaning that a new local variable sum is generated and saved each time the Exfunc function is called. In fact, the Exfunc function here is to return a closed packet.

According to the rules of the imperative language, the Exfunc function simply returns the address of the inline function Insfunc, and when the Insfunc function is executed, an error occurs because the sum variable is not found within its scope. In a functional language, when the inline function body refers to variables outside the body, the reference environment and function bodies involved in the definition are packaged into a whole (closure) return. The definition of a reference environment is now easy to understand: a reference environment is a collection of all active constraints (the name of a variable and the connection between the object it represents) at a point in the execution of the program. There is no difference between the use of closures and normal function calls.

Since closures package the function and runtime reference environment as a new whole, it solves the problem caused by nesting in function programming. As in the preceding code snippet, a new closure instance is returned each time the Exfunc function is called, and the instances are isolated, containing the different reference environment sites at the time of invocation. Unlike functions, closures can have multiple instances at run time, and different reference environments and the same combination of functions can produce different instances.

A closure function is a copy of the external data that is referenced to when it is created, together with the function to form a whole.

Conditions in which the closure function appears:
1. The nested function refers to external data that is not the function, and the external data is not a "global variable"
2. Functions are independent (returned or assigned to other functions or variables by the parent function)

Come back to see the definition of closures: what closures are, closures are entities that are composed of functions and their associated reference environments (that is, closures = functions + reference environments).

Objects are data with behavior, and closures are data-attached behavior

Reference: http://www.cnblogs.com/Jifangliang/archive/2008/08/05/1260602.html

Http://blog.sina.com.cn/s/blog_487109d101018fcx.html

 Package  Main
Import   "FMT"
func  exfunc (n int)  func() {
 sum : = N
 a : =  func() {
 sum++  //Add 1 to external data here
 FMT. PRINTLN (SUM)
    }
   return A
}
func  Main () {
 myFunc : = exfunc (ten)
 MyFunc ()
 myanotherfunc : = exfunc (a)
 Myanotherfunc ()
 MyFunc ()
 myanotherfunc ()  //The result here is 22, which proves two points
1. Modification of external data in closures, external not visible
2. The value of the external data is saved in the new static variable
}

Test

Look at the following scenarios, comparing the results of the execution

 
  Main
Import "FMT"
Main () {
int =5  
 a:=func()func() {
int =ten  
 FMT. Printf ("\neeee:%d\n", J)
func () {  
 FMT. Printf ("i,j:%d,%d\n", I,j)
        }
    }()
 A ()
 j*=2
 A ()
}
Execution Result:

Eeee:5
i,j:10,5
i,j:10,10
Exit code 0, process exited normally.

 
  

Example Two

 
  Main
Import "FMT"
Main () {
int =5  
 a:=func()func() {
int =ten  
 FMT. Printf ("\neeee:%d\n", J)
func () {  
 FMT. Printf ("i,j:%d,%d\n", I,j)
        }
    }
 A ()
 j*=2
 A ()
}
Execution Result:

Eeee:5

Eeee:10
Exit code 0, process exited normally.

Example Three

 
  Main
Import "FMT"
Main () {
int =5  
 a:=funcfunc() {
int =ten  
 FMT. Printf ("\neeee:%d\n", J)
func () {  
 FMT. Printf ("i,j:%d,%d\n", I,j)
        }
    }
 A () ()
 j*=2
 A () ()
}
Execution Result:

Eeee:5
i,j:10,5

Eeee:10
i,j:10,10
Exit code 0, process exited normally.

 
  
 
  

Resources:

Https://github.com/astaxie/build-web-application-with-golang/blob/master/02.3.md

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.