Go Language Learning Notes (v) [function]

Source: Internet
Author: User
Tags define function
This is a creation in Article, where the information may have evolved or changed. Date: July 29, 2014
1. Function definition: func (P type) funcname (q int) (r,s int) {return 0,0} func: reserved word, used to define a function (p type): optional, used to define a specific type of function, commonly known as a method. funcname: Name of function      (q int)  : Q as an input parameter, the function parameter in go is passed by the method of passing value. (r,s int) : The variable r,s is the named return value of the function, in go the function can return multiple values, if you do not want to name the returned parameters, you only need to provide the type: (int, int). If there is only one return value, you can omit the parentheses. If the function is a sub-procedure and there are no return values, you can omit the contents {return 0,0}: function body. Description: The order in which functions are defined can be arranged arbitrarily, and the compiler scans each file before execution. Go does not allow functions to be nested. However, you can use anonymous functions to implement it.
2, the function recursive example func rec (i int) {if i = = ten {return} rec (i+1) fmt. Printf ("%d", I)}
3. Function scope in Go, variables defined outside the function are global, variables defined inside the function are local to the function, and local variables are only valid when the function that defines it is executed. If naming overrides--a local variable has the same name as a global variable--when the function executes, the local variable overrides the global variable. Example: Package Main
var a = 6func main () {p ()
q () p () f () p ()}
Func p () {print (a)}func Q () {A: = 5 print (a)}func F () {a = 3 print (a)}
Printed results: 65633 Explanation: A is defined in function Q (), at which time the valid range of A is within Q (), and the function f (), A = 3 globally valid, A is re-assigned.
What is the scope of the function when it calls the function? Consider the following example:
Package Main
var a int
Func Main () {a = 5 print (a) f ()}func F () {A: = 3 print (a) g ()}func g () {print (a)}
Printed results: 535 explanation: Because a local variable is only valid when executing a function that defines it, a in G () uses an externally defined global variable.
4, multivalued return: Like Python, go also supports functions and methods to return multiple values. For example:Func Manyvaluereturn (x, y int) (int,int) {return x,x+y} call: X,z: = Manyvaluereturn (4,6) fmt. Printf ("x=%d,z=%d", x,z) execution Result: x=4,z=10
5. Named return value the return value of the Go function or the result parameter can specify a name and be used as the original variable, as if the input parameter is general. If they are named, they are initialized with 0 values of their type at the beginning of the function, and if the function executes a return statement without arguments, the current value of the resulting parameter is returned as the return value.    The names of the return values are not mandatory, but they can make the code more robust and clear. For example:
Example One (no named return value): func factorial (x int) int {if x==0 {return 1} else {return x * factorial (X-1)}} example one (named return value) : func factorial (x int) (result int) {if x==0 {return=1} else {return = x * factorial (X-1)} return}

In contrast to example one and example two, which looks clearer?
6. Variable parameter: The function of accepting an indefinite number of parameters is called the variable parameter function. For example: the func funcname (arg ... int) {},arg ... int indicates that the function accepts the argument, its parameter type is all int, and the variable arg is an int of type slice.
7. Anonymous function and Closure 1) anonymous function definition: A function implementation method that does not need to define function name. 2) Go language support defines anonymous functions in your code at any time. 3) Anonymous functions can be directly assigned to a variable or executed directly for example: package main
Import "FMT"
Func Main () {func (x, y int) {//function directly executes FMT. Println (x + y)} (5,6)//The argument list here represents a function call
F: = func (x, y int) int {///anonymous function as value assignment to f return x * y}
Result: = f (8,10) fmt. Printf ("result=%d", Result)}
4) Closure concept: Closures are blocks of code that can contain variables that are free (not bound to specific objects), that are not defined within this block of code 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. 5) The value of closures: The value of closures is that they can be used as function objects or as anonymous functions, 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. 6) Example of the closure function of the Go language: Func closefunc () {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//Modify J's value A ()} Execution Result: i,j:10,5i,j:10,10
Description: (1) The closure function of the variable a refers to the local variable j (local variable of closefunc) and I (local variable of the anonymous function), the value of I is isolated within the anonymous function and cannot be modified outside the closure. Change the value of J, call a again, and the result is the modified value. (2) In the closure function that the variable a points to, only the internal anonymous function has access to the variable I, thus guaranteeing the security of I.
8, function as a value can be assigned to a function as a value to a variable.           For example: A: = Func () {//Here is an anonymous function println ("hello!") }
9, error handling 1) Error interface: The go language introduces a standard pattern for error handling, the interface for errors. For most functions, if you want to return an error, you can roughly define it as the following pattern, with the error as the last (not mandatory) of the various return values. Func Foo (param int) (n int, err error) {} Call Yes code recommends handling error conditions as follows: N,err: = Foo (0) If err! = Nil {//error handling} else {//Use return value n} We can also customize the error type, which is not covered here. 2) Defer (1) there can be more than one defer statement in a function, so it is important to note that the call to the defer statement is in accordance with the advanced post-out principle that the last defer statement will be executed first. 3) Panic (panic) and Recover (recovery) (1) Go There is no exception mechanism like Java: An exception cannot be thrown. As an alternative, it uses the panic and recovery (panic-and-recover) mechanism. (2) There should be no or little scary things in the code.
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.