1, function
1) Statement
Function declaration includes a function name, a list of formal parameters, return a list of values (may be omitted), and functions thereof.
func function name (parameter list form) (the returned list) {
function body
}
If a function declaration, the list contains the return value, unless the function must be obvious at the end, the function ends with a return statement, not to run, such as a panic function calls or abnormal function in the presence of an infinite loop at the end.
Type of function is called a function identifier, and if the two functional form parameter list and return the list of variable types correspondence values, then the two functions are considered to have the same type and identifier, parameter and return value variable name does not affect the function identifier does not affect whether they can omit the parameter types represented in the form.
Every function must be provided when calling the declaration order for all parameter arguments (parameter values), the function call, Go language is no default parameter values, there is no way to specify parameter by parameter name, so formal and the return value of a variable name does not make sense for function calls are concerned.
In function, the argument values passed by way of transfer, so the function parameter is a copy of the argument, to modify the parameter argument does not affect, however, if the argument includes a reference type, such as pointers, Slice ( slice), map, function, channel type, etc., may be modified arguments since indirect reference function.
2) Return value
Go multi-language support return values, the return value and more ready access to multiple functions after the implementation of the return parameter.
Unnamed Return Value: If there is a plurality of return value, the return value enclose the plurality of enclosed type, the type of the return value of each separated by a comma.
Named return value: Go Language Support for naming the return value, such as parameters and return values to parameters have variable names and types. Name Default value return value of the variable type. In the embodiment of the return value name of the function body, need to explicitly use the return statement before the end of the function returns.
Named and non-named return value parameter can not be mixed.
Example:
package main import "fmt" func main() { x, y := add(1, 3) fmt.Println(x, y) a, b := sub(1, 3) fmt.Println(a, b) } func add(x, y int) (int, string) { return x + y, "hello" } func sub(x, y int) (a int, b string) { a = x - and b = "hello" return }
2, anonymous functions
1) the definition of
Anonymous function refers to a function need not be defined function name of implementation, the function declaration and the function body without a function name components.
Definition Format anonymous function is as follows:
func (parameter list) (return to the parameter list) {
function body
}
Anonymous functions can be called after the statement; anonymous function can be assigned.
Example:
package main import "fmt" func main() { func (str string) {// statement immediately after the call fmt.Printf("hello, %s\n", str) }("world") f := func(str string){ fmt.Printf("hello, %s\n", str) } f("world") }
3, the function type that implements the interface
Example:
package main import ( "fmt" ) // Call Interface type Invoker interface { // need to implement a method Call Call(interface{}) } // function is defined as type type FuncCaller func(interface{}) // Call Invoker of realization func (f FuncCaller) Call(p interface{}) { // call the function f body f(p) } func main() { // declare interface variables was Invoker Invoker // anonymous function into FuncCaller type, and then assigned to the interface invoker = FuncCaller(func(v interface{}) { fmt.Println("from function", v) }) // use interface calls FuncCaller.Call, calls the function inside the body invoker.Call("hello") }
4, closure
Go languages closure is a reference to the function of free variables, the free variables and functions referenced exist together, even though they have left the environment of free variables will not be released or deleted, the closure can continue to use the free variables.
As a function of the type of structure, as can be instantiated, the function itself does not store any information, only the formation of the closure after it has incorporated by reference environment "memory", is a function of static concept compiled, and the closure is dynamic concept runtime.
Its upper closure scope variables can be modified, modifying variables will be the actual reference variable changes.
5, variable parameters
1) The variable Parameter Type
The variable parameter is the number of arguments passed is variable, the function needs to be defined as a type of the variable parameter is acceptable.
func funcName(args ...type) {
}
... shaped like the type of format type only as a function of the type of the parameter is present, and must be the last argument , which is a syntactic sugar (syntactic sugar), i.e., the syntax of the language does not affect the function, but more convenient programmer, generally speaking, the use of syntactic sugar can increase the readability of the program, thereby reducing the possibility of a program error.
From the internal implementation mechanism, the type ... the type is essentially an array slice, that is, [] type, which is why the above parameters args can be used for cycles to get each incoming parameters.
Example:
package main import "fmt" func f(args ...int) { for _, arg := range args { fmt.Println(arg) } } func main() { f(1,2,3) }
2) any type of variable parameters
If you wish to transfer any type, you can specify the type of interface {}.
Example:
package main import "fmt" func MyPrintf(args ...interface{}) { for _, arg := range args { switch arg.(type) { case int: fmt.Println(arg, "is an 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() { was v1 = 1 v2 was int64 = 234 var v3 = "hello" var v4 float32 = 1.234 MyPrintf (v1, v2, v3, v4) }
3) passing a plurality of variable parameters in the parameter function
Variable parameter is a variable parameter that contains all slices, if you want to pass this variable contains the variable parameters of the function to the next variable parameter, the variable may be added to the time passed after the variable parameter ...
, so that the sections can be transfer elements, rather than passing the variable variable itself.
6、defer
Go language defer its statement will be followed by a statement delay processing, when the function is about to return attributable to defer (the end of the function can return to normal, it can be when downtime occurs), will be delayed according to defer processing of the statement reverse execution, that is to say, the first to be defer the final statement is executed, finally defer the statement, the first to be executed.
7、panic
When the panic () is triggered when downtime occurs, panic () behind the code will not be run, but () function has been run in front of the statement still defer action occurs panic when downtime occurs.
Example:
package main import "fmt" func main() { defer fmt.Println ( "after the downtime to do 1") defer fmt.Println ( "downtime to do after 2") panic ( "down") }
8、recover
Go language Recover is a built-in function that lets down into the flow of goroutine recover, recover only valid defer delay function in the normal course of implementation, call recover will return nil and have no other effect, if the current goroutine panic, call recover the input value can be captured to panic and resume normal execution.
Example:
package main import ( "fmt" "runtime" ) Context information needs to be passed when // crashes type panicContext struct { where the function string // function } // allow a protection function func ProtectRun(entry func()) { // function delay processing defer func() { // When downtime occurs, get panic passed and print context err := recover() switch err.(type) { case runtime.Error: // run-time error fmt.Println("runtime error:", err) default: // non-run-time error fmt.Println("error:", err) } }() entry() } func main() { fmt.Println ( "pre-run") // allow for some error triggered manually ProtectRun (func () { fmt.Println ( "hand down the front.") // Use the context transfer panic panic(&panicContext{ "Manual trigger panic", }) fmt.Println ( "after a manual down") }) fmt.Println ( "run") }
Panic and recover the composition has the following characteristics:
- There are panic did not recover, the program down.
- There are also panic recover, the program will not down, after you perform the corresponding defer, withdraw from the current function continues after downtime point.
Defer function in panic triggered, can continue to invoke panic, further throwing error outside until the whole program crashes.
If you want to set the return value of the current function when capturing error, you can use the return value named return value directly set.