[Journey with golang] 2. Function

golang function as the "first citizen", in:

  • Function is a type, function type variables can be used the same as other types of variables, as a function of other parameters or return values, may be performed directly call
  • Support multi Return Value Returns
  • Support closures
  • Support variable function

And other languages, including function declaration keyword func, function name, parameter list, and returns a list of the function body. Function names follow the naming rules for identifiers, the first letter of the function in the case decided the visibility of other packages: other packages visible uppercase, lowercase only when the same package can access.

Function can not return a value, this default will return 0.

Known function supports the return value, the function corresponding to the parameter name in vivo outermost local variable named return value of the variable is initialized to a zero value types, with the last name of the parameter may not return directly returns.

Function does not support default parameters, do not support overloading, nor does it support nested function definitions name (can be anonymous function).

Support multi-valued function returns an idiom is: If there is error type multi-value return, take it as the last return value.

golang function argument to the parameter passed is always a value copies, sometimes after the function call argument points to the value of change, it is because the parameters passed is a copy of the pointer value (not that pass pointers c ++ is?), real parameter is a pointer variable, the parameter is passed to a copy of this pointer variable, both point to the same address, the parameter value passed still inherently copies.

Variable parameters declared using  param ... type  this syntax. All variable parameters must be the same type, and the indefinite parameters must be the last parameter of the function. Variable parameter name in the body of the function corresponding to the slice, the slice are also suitable for the operation of variable operating parameters. Slice can be passed as a parameter to the variable parameters, followed by a slice name to add .... Undefined function parameter and shape parameter as a function of parameters of the slice is not the same type.

Signature function type called function, a function of the type defined in the first line is a function to remove the function name, and parameter name {may be used fmt.Printf formatting parameters of% T to print function type. The same two types of functions that: have the same parameter list and return a list of values ​​(the order of the list of elements, the number and type are the same), parameter names may be different.

Type can define the type of function type variables can function as a function of the parameters or return values.

Type and function map, slice, chan, the actual function of the type of variable and function names can be used as a pointer variable, the pointer points to the start position of the function code. Generally speaking, the type of function is a reference type variable, a function of the type of uninitialized variable defaults to nil.

Function name can be seen as well-known function of the type of constant function, you can directly call the function using the function name can be assigned directly to the function type variable.

Anonymous functions can be seen as a digital face amount. All places directly using the function type of a variable can be replaced by an anonymous function. Anonymous functions can be assigned directly to the function variables, can be used as arguments, can be used as a return value, it can also be called directly.

golang provided defer keywords, you can register multiple delayed call. These calls with last-out (FIFO) order is executed before the function returns. defer common language to ensure that some of the resources is eventually recycled or released. Behind defer must call a function or method, it can not be a statement, otherwise it will report expression in defer must be function call error.

Real defer when registering function parameters passed in by copying values. defer statement must register to perform, will not be executed if after defer located return. When the initiative to call os.Exit (int) to exit the process, defer no longer be executed.

Improper location defer statement may cause panic, generally defer statement following statement in error checking.

defer have significant side effects: defer to delay the release of resources, defer with respect to the normal function call needs to support indirect data structure, compared with the normal function call, there are some performance loss.

Closures are referenced by the combination of the physical environment and its associated functions, typically by an external reference a local variable in a function anonymous function or global variable configuration package. = + Closure function reference environment.

Introducing outside environment closure closure is referenced directly compiler detects the closure, the closure will be referenced external variables allocated to the heap.

If the function returns a reference to a local variable closure of the function:

  1. Call this function repeatedly, a plurality of external variables returned closures referenced multiple copies, because each call function will allocate memory for local variables.
  2. With a closure function multiple times, if the closure modify the external variables it references, then each time it is called closure affects both the external variables, because the closure function shared external reference.

If a closure function call returns a reference to modify the global variables, each call will affect the global variables. Closures are used to reduce the global variables, global variables so that the closure is not a good reference programmatically.

The original purpose of the closure is to reduce global variables, function calls in the process of transfer of implicit shared variable, has its useful side: but in this way brings hidden shared variable direct harm is not enough, not clear enough, unless it is very valuable place, generally we do not recommend the use of closures.

The object is accompanied by behavioral data, and the closure is attached to the data behavior.

golang provides two ways to handle errors, one is thrown by means of panic and recover capture mechanism, and the other is using the wrong type of error.

panic for active throws an error, and recover to catch errors panic thrown. Lead to panic, there are two cases, one is a program initiative to call panic function, the other is the program generates run-time error detection and thrown by the runtime.

After the panic occurs, the program returns from the function call panic position or place of occurrence of panic immediately, layer by layer to perform defer statement function upward, then layer by layer saphenous function call stack until it is captured or run to recover a function of the outermost layer drop out.

panic function not only thrown normal flow, where the defer logic may call again or throw panic panic, panic inside defer defer subsequent execution to be captured.

recover to capture panic, panic organizations continue to pass upward. Use recover and defer together, but the function of the body behind only defer recover directly invoked to capture the abnormal termination of panic, otherwise it returns nil, abnormal continue to pass out. There may be multiple consecutive panic was thrown out, but only the last panic can be captured.

Errors in the broad sense: undesired behavior. Narrow mistake: the occurrence of undesired known (refer to the type of error is to be expected and defined) behavior. Exception: Unknown (contrary to known) undesired behavior. Go is a type-safe language, compiler and runtime errors that can not be captured when it will not run, that is to say, does not appear untrapped error, so go there is no so-called exception from this perspective, "anomaly" appeared all wrong.

For golang provides two error handling mechanisms:

  1. To handle the type of error the error value returned by the function.
  2. Call stack by panic printing program, stops the program execution to handle errors.

So handling of errors, there are two ways, one is to handle the error by returning a value of the wrong type, the other is a direct call panic throw an error, exit the program.

Actual programming, error and panic use should follow the following three rules:

  1. Results of the implementation of local code does not meet expectations, but within the error range of predefined such behavior is not run-time error, such non-desired behavior does not cause the program can not provide services, such scenes should use the function returns the error type variables error handling.
  2. An error occurred during program execution, and the kind of error is within a predefined range of error run-time error, this time golang default action is to call the implicit deal with panic, if such a panic occurs in the branch flow of the program does not affect the main function, may be used recover a program branch is taken upstream of the capture panic, to avoid triggering a collapse of the entire process
  3. Local code execution result of the program does not meet expectations, though such behavior is not running predefined error within the error range, but this can lead to undesired behavior can not continue to provide services, such a scene in the code should take the initiative to call panic termination execution of the program.

go function uses caller-save mode, i.e., the caller is responsible for saving register, so the function will not be the head and tail assembly code push ebp; mov esp EBP this code, the called function call is opposite to the calling function there is a scene before and after the preservation and restoration of the site of action.

Go assembly code generated by the compiler is an intermediate state of abstraction, it is not mapped to the machine code, but a platform-independent intermediate state described so assembler code compilation Some registers are true, some are abstract, such as:

  • SB (static base pointer, the static base register), and global symbols which together represent the address of the global variables.
  • FP (frame pointer, stack frame register) register points to the function call stack bottom position of the current stack frame.
  • PC (program counter, a program counter), storing the address of the next instruction execution, the register little direct operation, typically CALL, RET instructions such implicit operation.
  • SP (stack pointer, the stack register), the space allocated to the general or recovered before the function call provided by the calling function value SP.

go inline assembly and disassembly of generated code is not one to one, assembler inline assembler to automatically make the adjustment, the main difference is to increase the protection of the site, as well as maintaining PC before the function call, SP offset weight positioning logic. Disassembly better reflect the true execution logic program.

Guess you like

Origin www.cnblogs.com/JHSeng/p/12141958.html