Golang Learning Notes-func functions

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.


Functional function



Listen and listen-the GO function does not support nesting, overloading, and default parameters



Listen and listen-but the following features are supported:



Listen, listen, hear and hear. No need to declare the original shape, variable length parameters, multiple return values, command return value parameters, anonymous functions, closures



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



Listen and listen-functions can also be used as a type to assign values directly to variables (anonymous functions)





Define a function



Listen to listen format: Func name (incoming variable 1 type, variable 2 type) [return variable type, variable type]{}



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



Listen and listen-when the passed variable type is the same, you can omit all but the last one



Listen, listen, listen, listen. Func a (a,b,c int) {}



Listen and listen-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 a variable to write each type, if the specified return a local variable, then the variable is already defined, then in the function body can be directly used.



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



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



Listen and listen to the Func A (a ... int) listen-->...int must be put in the last



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



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



Listen and listen-if you need to pass in and modify the values of int, string type, you need to pass in the memory address of these types of variables

package listen main
import listen to "fmt"
func listen main () listen {
Listen, listen to a: listen to = 2
Listen, listen to A (a)
Listen to listen to fmt.Println (a)
}
func listen A (a listen int) listen {
Listen, listen to i listen: = listen 3
Listen to listen to fmt.Println (i)
}
result:
3
2


Pass the address of variable a to the function

package listen main
import listen to "fmt"
func listen main () listen {
Listen, listen to a: listen to = 2
Listen & Listen A && Listen // & a means take the memory address of a
Listen to listen to fmt.Println (a)
}
func listen A (a listen * int) listen {listen listen listen // define the pointer type, point to the memory address of a
Listen, listen * a Listen = Listen 3, Listen, Listen, // directly assign the memory address
Listen, listen to fmt.Println (* a)
}
result:
3
3


Parameter transfer (pass value and pointer)

There are two types of parameter passing for functions, value passing and reference passing. Value passing refers to copying the actual parameters to the function when calling the function, so if the parameters are modified in the function, it will Will affect the actual parameters. By default, GO is passed by value and will not affect the actual parameters during the call.

Listen, listen to variables are stored in a certain address in the memory, modify the variable is actually to modify the memory at the address of the variable. Only when the local function knows the memory address of the parameter can the value of the variable be modified. Therefore, when the reference is passed, the memory address of the variable needs to be passed into the local function (& a, & means the memory address of the passed variable), and the parameter type of the function is adjusted to * int, which is changed to the pointer type, in order to be in the function Modify the value of the variable, at this time the parameter is still passed by copy, but copy is a pointer.



Functions as values of other variables

Listen to listen In Go, everything is a type, and functions can also be named as variables, and then call functions on the variables

package listen main
import listen to "fmt"
func listen main () listen {
Listen to listen to a to listen: = listen to A
Listen, listen to a ()
}
func listen A () listen {
Listen, listen to fmt.Println ("Func Listen A")
}
result:
Func Listen A


Anonymous function

Listen to listen. When you define a function, you do n’t specify the name of the function, but the function that assigns the function directly to a variable is called an anonymous function. When calling this function, you can use the name of the variable directly. (Because func in golang does not support function nesting, using anonymous functions can achieve nesting effects.) Listen Anonymous functions cannot be used as top-level functions (outermost layer)

package listen main
import listen to "fmt"
func listen main () listen {
Listen to listen to a to listen: = listen to func () listen {
Listen to listen to fmt.Println ("Func")
}
Listen, listen to a ()
}


Closure function

Listen to listen to the so-called closure function is to write the definition of the entire function in one go and assign it to a variable. Then use this variable name as the function name to call the function body. The closure function has access to and modification to the variables in its outer functions

package listen main
import listen to "fmt"
func listen main () listen {
Listen to listen to listen to: = listen to close (10) listen to listen to // call the closure function and pass 10
Listen to listen to fmt.Println (f (1)) Listen to listen // pass 1 to the returned function, 10 + 1 = 11
Listen to listen to fmt.Println (f (2)) Listen to listen // pass 2 to the returned function, 10 + 2 = 12
}
func listen to close (x listen to int) listen to func (int) listen to int listen {listen to listen // define a function to receive a parameter x, the return value is also a function to receive a variable y
Listen listen listen return listen func (y listen int) listen int listen {listen listen listen // return an int, the function receives a parameter, returns the value of x + y
Listen listen listen listen listen listen return listen x listen + listen y
Listen listen listen
}
result:
11
12


defer

Listen to listen-the execution method is similar to the destructor in other languages, after the function body is executed, it is executed one by one in the reverse order of the calling sequence (similar to the stack method, first in, first out, last in first out)

Listen, listen-even if a serious error occurs in the function

Listen, listen-support anonymous function calls

Listen, listen, listen-common language resource cleaning, file closing, unlocking, recording time and other operations

Listen to listen-by working with an anonymous function, you can modify the function calculation result after return

Listen to listen-if a variable in the function body is used as the parameter of the anonymous function when defer, then you have obtained a copy when defining the defer, otherwise it is the address of a variable

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

Listen, listen-Panic can be triggered anywhere, but recover is only valid in the function called by defer

example

package listen main
import listen to "fmt"
func listen main () listen {
Listen, listen to fmt.Println ("a")
Listen, listen to defer, listen to fmt.Println ("1")
Listen, listen to defer, listen to fmt.Println ("2")
Listen listen listen defer listen fmt.Println ("3")
}
result:
a
3
2
1
It can be seen that after the program is executed, defer is executed from the last statement, which proves that defer operates like a stack


The result of the defer collocation cycle

package listen main
import listen to "fmt"
func listen main () listen {
Listen to listen to listen to listen to: = listen to 0; listen to i <list 3; listen to i ++ listen {
Listen listen listen defer listen fmt.Println (i)
Listen listen listen
}
result:
2
1
0


panic / recover instance

Mainly used to control the program, and only collect and callback for function-level errors. So that the program can continue to run

package listen main
import listen to "fmt"
func listen main () listen {
Listen, listen to A ()
Listen, listen to B ()
Listen, listen to C ()
}
func listen A () listen {
Listen, listen to fmt.Println ("A")
}
func listen B () listen {
Listen listen listen defer listen func () listen {listen listen listen // defer executes an anonymous function to capture panic, here if put defer after panic then the program will crash after panic is executed, then defer Will not take effect
Listen listen listen listen listen listen listen if listen err listen: = listen recover (); listen err listen! = Listen nil listen {listen listen listen // judge the panic caused, because the panic is triggered manually and the message is sent , Then the return value of the exception received by recover should not be empty. If it is nil, there is no exception, and if it is not nil, it means an exception. Here we judge the return value of recover
Listen listen listen
} ()
Listen to listen to panic ("this listen to listen to pain") // Send abnormality, the exception message is "this listen to listen to panic"
}
func listen C () listen {
Listen, listen to fmt.Println ("C")
}
result:
A
C
Because the abnormal recovery mechanism is defined in function B, it will not force the program to exit and will continue to execute
panic / recover example 2

package listen main
import listen to "fmt"
func listen main () listen {
Listen, listen to fmt.Println ("1")
Listen to listen to fmt.Println ("2")
Listen to listen to f to listen: = listen to func () listen {
Listen listen listen listen listen listen defer listen func () listen {
Listen listen listen listen listen listen listen listen listen listen listen listen err listen: = listen recover (); listen err listen! = Listen nil listen {
Listen listen listen listen listen listen listen listen listen listen fmt.Println ("panic")
Listen listen listen listen listen listen listen listen listen listen}
Listen listen listen listen listen listen listen) ()
Listen to listen to panic ("hello listen to world")
Listen to listen to fmt.Println ("7")
Listen listen listen

Listen, listen to f ()
Listen to listen to fmt.Println ("8")
Listen listen listen
result:
1
2
panic listen listen listen listen listen print panic shows that the program has successfully caught the exception
8


Listen to listen, the anonymous function is defined and assigned to the variable f, the "7" in the anonymous function will not be printed, because the panic has been crashed after the execution, and we have defined recover capture in the anonymous function, so the anonymous function will Was quit, and then continue to execute other programs



Extension:

Listening to listening There is no exception catching mechanism in go language. Errors are captured and handled through panic / recover. The concept of multi return value of go function is used to check. If err is equal to nil, no error has occurred. The program has a serious error that is too serious to make up for. For example, the index is out of bounds. Because we cannot accurately determine the number of elements, recover is meaningless, so this time it is a panic. If you know that the index may be out of bounds, and hope that the program can recover from the error, then you need to use recover. Once you call recover, the system will think that you need to recover from the panic state. When the program enters the panic state, it is normal. The program will not be executed, so you need to define defer to execute recover (). Defer will be executed regardless of any state. As long as you put recover in defer, the program will reply no matter what error occurs in the program. It should be noted that the defer is similar to the stack mode, last in first out. Before the panic program may occur, define the defer in advance, otherwise the program will crash directly after running to pain. At this time, he will only check the pre-defined defer, and after you put it in the panic, it will be invalid.



Example 1:

Judge parity

package listen main
import listen to "fmt"
func listen main () listen {
aListen: = listen [] int {1, listen 2, listen 3, listen 4, listen 5, listen 6, listen 7, listen 8, listen 9, listen 10, listen 11, listen 12, listen 13, listen 14}
Listen to listen to fmt.Println ("the listen to slice listen to is listen", listen to a)
Listen to listen to fmt.Println ("the listen to listen to is listen", listen to odd (a))
Listen, listen to fmt.Println ("the listen even listen to is listen", listen even (a))
}
func listen odd (num listen [] int) listen [] int listen {
Listen listen listen var listen result listen [] int
Listen to listen to listen to listen to listen to listen_, listen to value listen: = listen to range listen to num listen {
Listen to listen to listen to listen to listen to listen to listen to listen to listen if listen to value% 2 listen == listen 0 listen {
Listen listen listen listen listen listen listen listen listen listen listen listen listen listen listen listen listen listen (result, listen value)
Listen listen listen listen listen listen listen listen listen listen}
Listen listen listen listen listen listen listen}
Listen listen listen return listen result
}
func listen even (num listen [] int) listen [] int listen {
Listen listen listen var listen result listen [] int
Listen to listen to listen to listen to listen to listen_, listen to value listen: = listen to range listen to num listen {
Listen to listen to listen to listen to listen to listen to listen to listen to listen if listen to value% 2 listen == listen 0 listen {
Listen listen listen listen listen listen listen listen listen listen listen listen continue
Listen listen listen listen listen listen listen}
Listen to listen to result listen = listen append (result, listen to value)
Listen listen listen
return listen result
}


Idea: Filter the slices separately, filter the even-numbered function module once to pick out the even number, and filter the odd-numbered function module once to pick out the odd number. Disadvantages, poor module reuse.



Determine the parity:

package listen main
import listen (
Listen to listen to "fmt"
)
type listen funcation listen func (int) listen bool
func listen odd (num listen int) listen bool listen {
Listen listen listen listen if listen num% 2 listen == listen 0 listen {
Listen listen listen listen listen listen return listen false
Listen listen listen
Listen listen listen return listen true
}
func listen even (num listen int) listen bool listen {
Listen listen listen listen if listen num% 2 listen == listen 0 listen {
Listen listen listen listen listen listen return listen true
Listen listen listen listen listen listen listen}
Listen listen listen return listen false
}
func listen filter (slice listen [] int, listen f listen funcation) listen [] int listen {
Listen listen listen var listen result listen [] int
Listen to listen to listen to listen to listen to listen_, listen to value listen: = listen to range listen to slice listen {
Listen listen listen listen listen listen listen listen listen listen listen listen listen f (value) listen {
Listen listen listen listen listen listen listen listen listen listen listen listen listen listen listen listen listen listen (result, listen value)
Listen listen listen listen listen listen listen listen listen listen}
Listen listen listen listen listen listen listen}
Listen listen listen return listen result
}
func listen main () listen {
Listen, listen, listen a: = listen [] int {1, listen 2, listen 3, listen 4, listen 5, listen 6, listen 7, listen 8, listen 9}
Listen to listen to fmt.Println ("the listen to slice listen to is listen", listen to a)
Listen to listen to fmt.Println ("the listen to listen to is listen", listen to filter (a,Listen odd))
Listen, listen to fmt.Println ("the listen even listen to is listen", listen filter (a, listen even))
}


Idea: Modulate the function of judging parity, and then adjust the parity judging module through a module, and then organize it with the main function (using the func type to pass the functional module), a bit, strong structure and strong logic.



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

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.