Golang Learning Notes-func functions

Source: Internet
Author: User

Functional function

-The GO function does not support nesting, overloading, and default parameters

-however, the following features are supported:

No need to declare a prototype, variable length parameter, multiple return value, command return value parameter, anonymous function, closure

-The definition function uses the keyword func, and the curly brace cannot be another line (all curly braces follow this principle)

-functions can also be used as a type, directly assigned to variables (anonymous functions)

Define a function

Format: Func name (incoming variable 1 type, variable 2 type) [return variable type, variable type]{}

    - the passed-in variable can be either not, or you can make multiple

-When the passed variable type is the same, you can omit all but the last one

Func A (a,b,c int) {}

-The return value can have more than one, the return value type is the same, you can only leave the last one, where the return variable name can be omitted, omitted, it is necessary to return each of the type of a variable, if it is specified to return a local variable, then the variable is already defined, then in the function body can be directly used.

-Do not specify the return variable name, then you need to write the return variable 1 at the end of the function, the variable 2, if you specify the name of the variable returned, then you need to write only the return.

-The number of parameters passed in, can also be variable (indefinite long parameter), use ... To indicate that the type of data stored in the function body is slice

Func A (a ... int)-->...int must be put in the last

-If the passed-in value has 1 strings, and there are n int, then only fun A (b string, a ... int) is accepted in this form

-If the passed-in parameter is a regular int, string, and so on, is a value pass (the default), which is only worth copying, and if passing sllice, it is a reference pass (in fact, slice is also a value copy, but slice copy of the memory address. Modifying the memory address directly affects the source data)

-If you need to pass in and modify the value of int, string type, then you need to pass in the memory address of these types of variables

Package Mainimport "FMT" Func Main () {A: = 2 A (a) fmt. Println (a)}func a (a int) {i: = 3 fmt. Println (i)} results: 32


Pass the address of variable a into the function

Package Mainimport "FMT" Func Main () {A: = 2 A (&a)//&a represents the memory address of a (FMT). Println (a)}func a (a *int) {//define pointer type, point to a memory address *a = 3//Assign the memory address directly to the FMT. Println (*a)} results: 33


Parameter passing (passing and passing pointers)

The parameter passing of a function is divided into two types, value passing, and reference passing, and value passing means that the actual parameters are copied to the function when the function is called, so that if the parameters are modified in the function, the actual parameters will not be affected. By default, go is a value pass that does not affect the actual parameters during the call.

Variables are stored at a certain address in memory, and modifying variables is actually the memory at the address of the modified variable. You can modify the value of a variable only if you have the local function know the memory address of the parameter. So when the reference is passed, the memory address of the variable must be passed into the local function (&a,& the memory address of the passed variable), and the parameter type of the function is adjusted to *int, that is, the pointer type is changed so that the value of the variable can be modified in the function, and the parameter is still passed by copy. Just copy is a pointer.


function as the value of other variables

In the go language, all types, functions can also be named variables, and then function calls to the variables

Package Mainimport "FMT" Func Main () {A: = a A ()}func a () {FMT. Println ("Func a")} Result: Func a


anonymous functions

When defining a function, instead of specifying the name of the function, the function that assigns the function directly to a variable is called an anonymous function, and the name of the variable is used directly when invoking the function. (because func in Golang does not support function nesting, nested effects can be achieved using anonymous functions) Anonymous functions cannot be a top-level function (outermost)

Package Mainimport "FMT" Func Main () {A: = Func () {fmt. Println ("Func")} A ()}


Closure function

The so-called closure function is the definition of the entire function one go written and assigned to a variable. Then use this variable name as the function name to call the function body. The closure function has permission to access and modify variables in its outer function.

Package Mainimport "FMT" Func main () {f: = Closure (10)//Call closure function and pass the ten FMT. Println (f (1))//pass 1 to the returned function, 10+1=11 FMT. Println (f (2))//pass 2 to function returned, 10+2=12}func closure (x int) func (int) int {///define a function to receive a parameter x, return value is also a function to receive a variable y return func (y int) int {//returns an int, the function receives a parameter that returns the value of X+y return x + y}} results: 1112


Defer

-execution is similar to destructors in other languages, executed one after the end of the function body in the reverse order of the call order (similar to the stack Way, FIFO, LIFO)

-executes even if the function has a critical error

-Support for anonymous function calls

-Common Language resource cleanup, file closing, unlocking, and recording time

- Modify function calculation result after return by cooperating with anonymous function

-If a variable in the function body is a parameter of an anonymous function when defer, then a copy is obtained when the defer is defined, or the address of a variable is referenced

-Go has no exception mechanism, but has panic/recover mode to handle errors

-Panic can be thrown anywhere, but recover is only valid in functions called by defer

Example

Package Mainimport "FMT" Func Main () {FMT. Println ("a") defer FMT. Println ("1") defer FMT. Println ("2") defer FMT. Println ("3")} results: A321 can see that, after the execution of the program, defer is executed from the last statement, proving how the defer like stacks run


Defer results with loops

Package Mainimport "FMT" Func Main () {for i: = 0; i < 3; i++ {defer fmt. Println (i)}} results: 210


Panic/recover instances

It is primarily used to control the program and only collects and callbacks for function-level errors. To keep the program running.

Package Mainimport "FMT" Func Main () {a () B () C ()}func A () {fmt. Println ("A")}func B () {defer func () {//define defer here to execute an anonymous function for capturing panic, if the defer is placed after panic then the program will crash after panic, then defer will not Effective if err: = Recover (); Err! = Nil {//To judge the panic that is raised, because the panic is triggered manually and the message is sent, the return value of the exception received by recover is not NULL, and if nil means no exception, then nil means an exception. The return value of Recover}} () Panic ("This is Painc")//sends an exception with the exception message "This is Panic"}func C () {fmt. Println ("C")} Result: AC because the recover mechanism of the exception is defined in function B, it does not force the program to exit and continues execution

Panic/recover Example 2

package mainimport  "FMT" Func main ()  {     fmt. Println ("1")     fmt. Println ("2")     f := func ()  {         defer func ()  {            if  Err := recover (); err != nil {             fmt. Println ("Panic")             }         } ()     panic ("Hello world")     fmt. Println ("7")     }    f ()     fmt. Println ("8")      results: 12panic      //Printing Panic The program has successfully caught an exception 8 


The anonymous function is defined and assigned to the variable F, and the "7" in the anonymous function does not print, because execution to panic has crashed, and we have defined the recover capture within the anonymous function, so the anonymous function is exited, and then the other program continues to execute


Extended:

In the Go language is no exception capture mechanism, through the panic/recover to achieve error capture and processing, using Go function multiple return value concept, to check, if Err equals nil to indicate that no error occurred, when the program has serious errors, serious to irreparable, For example, index out of bounds, because we can not accurately determine the number of elements, so recover also meaningless, so this time is a panic. If you know that the index may be out of bounds, and you want the program to return from the error, then you need to use recover, once called recover, the system will think you need to recover from the panic state, when the program enters the panic state, then the normal program will not be executed, Then need to define defer to execute recover (), defer no matter in any state, will be executed, as long as the recover in defer, then no matter what happens to the program, the program will reply, need to pay attention to defer similar stack mode, LIFO. Pre-defined defer in the event of a possible panic program, or the program runs to Painc and crashes directly, this time he will only check the pre-defined defer, and after you put it in panic, it will fail.


Example 1:

Judging odd even numbers

package mainimport  "FMT" Func main ()  {a := []int{1, 2, 3, 4,  5, 6, 7, 8, 9, 10, 11, 12, 13, 14}    fmt. Println ("the slice is ",  a)     fmt. Println ("the odd is ",  odd (a))     fmt. Println ("the even is ",  even (a))}func odd (Num []int)  []int {     var result []int        for _,  value := range num {             if value%2 == 0 {                 result = append (Result, value)              }        }&nbSp;   return result}func even (Num []int)  []int {     var result []int        for _, value :=  range num {            if  value%2 == 0 {                 continue        }    result  = append (result, value)     }return result}


Idea: The slice is filtered separately, even function module filter once, pick out even, odd function module filter again, pick surprisingly number. Disadvantage, the module reusability is poor.


Judge Odd even:

package mainimport  (     "FMT") type funcation func (int)  boolfunc  odd (Num int)  bool {    if num%2 == 0 {         return false    }     Return true}func even (Num int)  bool {    if num%2 ==  0 {        return true         }    return false}func filter (slice []int, f  Funcation)  []int {    var result []int         for _, value := range slice {             if f (value)  {             &nbsP;   result = append (Result, value)              }        }    return  result}func main ()  {    a := []int{1, 2, 3, 4,  5, 6, 7, 8, 9}    fmt. Println ("the slice is ",  a)     fmt. Println ("the odd is ",  filter (a, odd))     fmt. Println ("the even is ",  filter (A, even))}


Idea: The function of the judgment parity is modular, and then through a module to tune the odd and even judgment module, and then the main function of the organization, (using the Func type, the function module transfer), a bit, strong structure, strong logic.


This article is from the "Your Night" blog, be sure to keep this source http://lixin15.blog.51cto.com/3845983/1851888

Golang Learning Notes-func functions

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.