This is a creation in Article, where the information may have evolved or changed. # The basic composition of function #go language functions include: keyword func, function name, parameter list, return value, function body and return statement. # #函数定义这里举个简单的例子来说明一下Go语言中函数的定义问题: Func sumfunc (a int, b int) Int{return A + b} can be simplified when the type of formal parameter is the same: Func Sumfunc (A, b int) in The definition of a function for the T {return a + B} is not very different from other languages except that it has more than one keyword func. Here you need to take note of a concept * * Function identifier * *. The type of the function is called the identifier of the function. If the two function-form argument list and the variable type one by one in the return value list correspond, then the two functions are considered to have the same type and identifier. You can use the following code to print the type of the above function FMT. Printf ("%t\n", Sumfunc)//func (int, int) int You may occasionally encounter a function declaration without a function body, which means that the function is not implemented with go. Such a declaration defines the function identifier. Package Math func Sin (x float64) float//implemented in assembly language***# #多返回值在Go语言中, you can return multiple function values at once, as the previous example has said, For example, look at one of the following code to download a picture from the Internet: Func getpicurl (Movi_name string) (*picurl, error) {resp, err: = http. Get (URL + movi_name + KEY) if err! = Nil {return nil, err}if resp. StatusCode! = http. Statusok {resp. Body.close () return nil, FMT. Errorf ("Search query failed:%s", resp. Status)}var result picurlif err: = json. Newdecoder (resp. Body). Decode (&result); Err! = Nil {resp. Body.close () return nil, Err}resp. Body.close () fmt. Println (result. Pictureurl, MOVI_name) saveimage (result. Pictureurl, Movi_name) return &result, nil} Here is a picurl pointer and error, and the error is nil after the code has run properly. If a function will display the variable name for all the return values, then the return statement of the function can omit the operand. This is called bare return. As the above code can be written: Func GetPicUrl1 (Movi_name string) (Picurl *picurl, err error) {resp, err: = http. Get (URL + movi_name + KEY) if err! = nil {Return}if resp. StatusCode! = http. Statusok {resp. Body.close () return}if err = json. Newdecoder (resp. Body). Decode (&picurl); Err! = Nil {resp. Body.close () Return}resp. Body.close () fmt. Println (Picurl. Pictureurl, Movi_name) saveimage (Picurl. Pictureurl, Movi_name) the benefit of Return}bare return is that many return values are convenient to write. But the readability of the code becomes worse, so try not to use it. # #错误处理Go语言引入了3个关键字用于标准的错误处理流程, these 3 keywords are defer, panic, and Recover:type error interface {error () string} So for functions that might return an error, The following pattern can be set roughly, and error is generally used as the last return value: Func func (para int) (i int,err error) {}_,err: = func (4) If err! = nil{//Handling Error}else{//normal code handling}** *# #函数值Go语言提供了函数值的功能, you can use a function as a value: Func Funcvalue (A, b int) int {return a + B}funcvalue: = FuncValuefuncvalue2: = Func (A, B in T) int {return a * b}fmt. PrIntln (Funcvalue (1, 2)) fmt. Println (Funcvalue2 (3, 4)) ***# #匿名函数在Go里面, the anonymous function is similar to the C-language callback function. But the go language can define anonymous functions at any time inside the function. * * functions defined in this way can access the complete lexical environment (lexical environment), which means that intrinsic functions defined in the function can reference the variables of the function. **//directly defines an anonymous function funcvalue2: = Func (A, b int) int { Return a * b}funcvalue2 ()//Returns an anonymous function within the function func Anonymousfunc () func () {var sum intchildfunc: = Func () {sum++fmt. Println ("The sum is", sum)}return Childfunc} If the above anonymous function takes the following invocation: func1: = Anonymousfunc () func1 () func1 () func1 () The result will be func1: = Anonymousfunc () The sum is 1The sum are 2The sum is 3 This shows that the sum variable and the anonymous function exist simultaneously, and when you perform an anonymous function func1, the value of sum is persisted. This involves another concept, * * closures. Closure the personal understanding is that the inner layer function can access the outer variables, but the outer layers cannot access the inner variables. # #可变参数参数可变的函数称为可变参数函数, like our FMT println, this package is a typical variable-parameter function. Variable parameter func unstableparam (vals ... int) {For I, Val: = Range Vals {fmt. Println (i, Val)}}unstableparam (1, 2, 3, 4, 5) Unstableparam (1, 2) Use the following code if you use slice as a parameter: myslice: = []int{10, 11, 12, 13, 1 4}unstableparam (Myslice ...) As with the Append function, the principle should be to break the myslice into one element and then pass it to the function. # #Deferred函数defer是GO语言里面很有用的一个特性, let's take a look at the following example: Func Getpicurl (movi_name String) (*picurl, error) {resp, err: = http. Get (URL + movi_name + KEY) if err! = Nil {return nil, err}if resp. StatusCode! = http. Statusok {resp. Body.close () return nil, FMT. Errorf ("Search query failed:%s", resp. Status)}var result picurlif err: = json. Newdecoder (resp. Body). Decode (&result); Err! = Nil {resp. Body.close () return nil, Err}resp. Body.close () fmt. Println (result. Pictureurl, Movi_name) saveimage (result. Pictureurl, Movi_name) return &result, nil} This is the function that was written earlier to get the contents of the JSON file and download the picture, and you can see the resp. Body.close () This function was called many times. At this point we can write the following code directly: Func getpicurl (Movi_name string) (*picurl, error) {resp, err: = http. Get (URL + movi_name + KEY) if err! = Nil {return nil, err}if resp. StatusCode! = http. Statusok {return nil, fmt. Errorf ("Search query failed:%s", resp. Status)}var result picurlif err: = json. Newdecoder (resp. Body). Decode (&result); Err! = Nil {return nil, Err}defer resp. Body.close () fmt. Println (result. Pictureurl, Movi_name) saveimage (result. Pictureurl, Movi_name) return &result, Nil}**deferThis is done after the program exits, no matter what the form exits. Therefore, defer has a great effect on file processing and lock operations. * * See an example of defer: Func Tteratepara () {for i: = 0; i < 3; i++ {defer func () {fmt. Println (i)} ()}}func Tteratepara () {for i: = 0; i < 3; i++ {A: = Idefer func () {fmt. Println (A)} ()}}tteratepara () The only difference between the above two functions is that the following function defines a local variable a separately, passing a to the function behind defer. Output of two functions: 333 and 210. This is because the function records the memory address of I, not the value of a certain moment. So the value of I is finally 3.***# #Panic () and recover () The Go language introduces these two functions to handle errors during program operation. The Go type system captures many errors at compile time, but some errors can only be checked at run time, such as array access, null pointer references, and so on. These run-time errors can cause painc exceptions. It is also possible to trigger panic errors directly through the panic function. * * In general, when an panic exception occurs, the program interrupts the operation and immediately executes the deferred function (defer mechanism) in the goroutine (which can be understood as threads, described in detail in chapter 8th) * * See Example: Func errprocess () {Panic (" WWX ")}func Main () {errprocess () fmt.println (" Hello ")} so that Hello is not output, because panic will terminate the Goroutine (which can be understood as a line enters upgradeable). But sometimes there are exceptions that we don't want to terminate the entire thread directly. This is the time to use the Recover function. The Recover function can capture this exception directly and no longer escalate to the previous layer. What do you mean, that? Assuming that the function Funa called the function Funb,funb and call the function func, if the func generates a panic exception, if there is no recover function, then the exception will be escalated to Funb, if Funb does not exist recover, will be escalated to Funa, Until the beginning of the whole goroutine. So if you want to print out the following hello, you need to use the Recover function in errprocess to catch the exception: Func errprocess () {defer func () {if p: = Recover (); P! = Nil {fmt. PRINTLN ("Internal error:%v", P)}} () Panic ("wwx")}174 clicks
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.