This is a creation in
Article, where the information may have evolved or changed.
function func
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")} |