"Go Learning note" 9, function func

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

function func

    • The GO function does not support nesting, overloading, and default parameters
    • But support features

      • No need to declare prototypes, variable length arguments, multiple return values, named return value parameters
      • Anonymous functions, closures
    • The definition function uses the keyword func, and the opening brace cannot be another line

    • Functions can also be used as a type
1234567891011121314151617181920212223
//commom func main() {a,b,c,d: =1,2,3,4Test (A,B,C,D)} func test(s ... int) {FMT. Println (s)}//closure func main() {Test: = Test (1) FMT. PRINTLN (Test (1))} func test(a int) func(int)  int {return  func(b int) int {returnA + b}}

Defer

    • Execution is similar to destructors in other languages, and is executed one by one in the reverse order of the call order, after the function body execution finishes
    • Even if the function has a critical error, it will execute
    • Calls that support anonymous functions
    • Often used for resource cleanup, file closing, unlocking, and recording time
    • You can modify the function calculation result after return by cooperating with the anonymous function
    • If a variable in the function body is an argument to an anonymous function when defer, the copy is obtained when the defer is defined, or the address of a variable is referenced.

    • Go has no exception mechanism, with Panic/recover mode to handle errors

    • Panic can be thrown anywhere, but recover is only valid in functions called by defer
12345678910111213141516171819202122
 func main() {A () B () C ()} func A() {FMT. Println ("Func A")} func B() {defer  func() {ifERR: =Recover(); Err! =Nil{FMT. Println ("Recover in B")}}()Panic("Panic in B")} func C() {FMT. Println ("Func C")}

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.