The function of first knowledge of Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. statement: func funcName (input1 type1, Intput2 type2) (output1 type1, Output2 type2) { ............
//can have multiple return values
return val1, Val2
} Description: A function is declared in Golang through Func, the function can have one or more parameters, each parameter followed by a type, through, delimited, function can return multiple values, the number of returns to be defined at the time of the declaration of the same number of returns, declaration can not write the return of the variable name, The direct use of the type (if there is only one return value and does not declare the return value variable, you can omit the return value of the parentheses, if there is no return value, then directly omit the final return information definition) Example: func sumandproduct (A, b int) (int, int) { return a+b, A*b
} func sumandproduct (A, B int) (add int, multiplied int) { add = a + B;
multiplied = a * b;
return
} Both of these codes are correct, and when the function is defined, the command returns a parameter variable, which can be returned directly without the variable name. Note: If the return parameter of the command has the same name as a variable in the function code block, he will be hidden and the return result will be displayed, and the explicit return would first modify the named return value before executing the DEFER delay statement.
parameter variable parameters: Golang supports arguments, the category of all parameters in the variable must be the same, and must be the last parameter. Gets the variable parameter as a slice within the function. The function declaration is: func FuncName (args ... int) {} args ... int tells go that the function accepts parameter parameters. Use such as SUM (X[2:6] ...)
Use of parameters: The parameters of the function are copy-assigned, only the copy value and the copy pointer, and the pass-through pointer uses the "& Variable name", "Variable name * type" in the function declaration, such as: func Add (num *int) int { *num = *num +
Return *num
} use, Nmber: = + Add (&number) fmt. PRINTLN (number) in the Go language, string,slice,map these three types implement mechanisms like pointers, so they can be passed directly without having to fetch the address and pass the pointer. If the function needs to change the slice length, then the address pass pointer is still required.
anonymous functions and closures:

closures and anonymous functions are often used together, and you can use a closed package to access a local variable in a function (the variable being accessed refers to a pointer to a relationship, and the same local variable is manipulated), such as:

Func closure (x int) (func (), func (int)) {    fmt. Printf ("Initial value x is:%d, memory address:%p\n", X, &x)    f1: = Func () {        x = x + 5        fmt. Printf ("x+5:%d, memory Address:%p\n", X, &x)    }    F2: = func (y int) {        x = x + y        fmt. Printf ("x+%d:%d, memory Address:%p\n", y, X, &x)    }    return F1, F2}func main () {    func1, Func2: = Closure (Ten)    Func1 (    func2)    Func2 (20)}
the output is:
Initial value x is: 10, memory address: 0xc080000038
x+5:15, memory address: 0xc080000038
x+10:25, memory address: 0xc080000038
x+20:45, memory address: 0xc080000038

Deferred statement defer:
Golang, there is a statement defer statement, when the function is executed to the end, these defer statements are executed in reverse order of the definition, and when these defer statements are executed, the function returns again. All can use this to carry out resource security shutdown, unlock, record execution status, etc. Defer is the use of advanced post-out mode, such as stacks. Note: Defined deferred operations, where a copy of the value occurs if a parameter is supplied, although these functions are executed at exit, the parameter used is a copy of the definition, the principle of the copy, and the assignment principle of the variable, Slice,map,channel is a pointer copy.

functions as values, types: in Golang, a function is also a variable that can be defined by using type, which is a type that has all the same parameters and the same return value. type TypeName func (input1 type1, Input2 type2) (output1 type1, Output2 type2) A function as a type can pass a function of this type as a value, such as a composite method in an object-oriented way, such as: //Declare a function type type handlernum func (int) int
func Add (num int) int { sum: = 0
For I: = 1; i <= num; i++ {
sum + = i
    }
return sum
}
func Product (num int) int { return (1 +) * 100/2
}
func Gauss (num int, h handlernum) { return H (NUM)
}
Gauss (+, ADD) and Gauss (Product) have the same results for both functions.
panic and recover: there is no exception mechanism in Golang, it can not throw exception, but use panic and recover mechanism, panic it will interrupt the original control flow, and enter a panic process, when the function call panic, the execution of the original function will be interrupted, But the defer function in the original function executes normally, and then the function returns to the place where it was called. . Where called, the function behaves as if the panic was called, and the process continues up until all the called functions in the gorutine that occur panic return, at which point the program exits. Panic can be directly called panic generation, or there can be run-time errors generated. Recover can restore goroutine into the panic process, recover is only valid inside the defer delay function, and during normal execution, call recover returns nil, and no other task effect, If the current goroutine is in panic, call recover can capture the input value of panic and resume normal program execution.
the main function and the init function: Golang two reserved functions, the INIT function can be applied to all package,main functions can only be applied to the main package, two functions in the definition can not have any parameters and return value, a package can have more than one init function, However, for readability it is strongly recommended that the user write only one init function per file in a package, and the main function has a main packet. program initialization and execution start from the main package, if the main package also imports other packages, they will be compiled at compile time they import, when a package is imported at the same time, then it will be imported only once, when the imported package also introduced other packages, then the other packages will be imported into the first, The package-level constants and variables of these packages are then initialized, followed by the Init function, and so on, and so on, when all the imported packages are loaded and initialized, the package-level constants and variables of the main package are initialized, and then the INIT function in the main package is executed. Finally, the main function is executed. The process of Const->var->init->main.
built-in functions: Close : The channel is closed. Len: Gets the length of the String,array,slice, the number of map keys, and the amount of data available in buffer channel. cap: Gets the array length, the slice capacity, and the maximum cache capacity of the buffer channel. NEW: Allocates the initialized memory space (0 value padding) to the specified type and returns a pointer. Make : Used only for slice, map, channel pointer assignment types, in addition to initializing memory, it is also responsible for setting related properties. Append: Appends one or more elements to the tail of the slice. Copy : Copies data between different slice and returns the number of copies, such as copy (S1, S2[2:7]) panic/recover: Error Handling complex/real/imag: plural processing.
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.