This is a creation in Article, where the information may have evolved or changed.
It's almost like the C language. |
Example |
Description |
function format is different |
Func getmsg (i int) (R string) { Fmt. Println (i) r = "HI" Return r } |
Func indicates that this is a function Getmsg is the name of the function The (i int) function receives an int parameter The (R string) function returns a string of type return value |
The
function can return multiple return values |
Func getmsg (i int) (r string, err string) { fmt. Println (i) r = "HI" err = "No" err " return r,err } |
This is not the same as C, PHP, and Lua is the same. |
Use of defer |
Func ReadFile (FilePath string) () { File. Open (FilePath) defer file. Close () If True { File. Read () } else { return False } } |
Defer means "call on function exit", especially when reading and writing to a file, you need to call close after open, and the close operation uses defer, which is written in file. Close is not immediately called after open, and file is called when return is false. Close (). This effectively avoids the problem of memory leaks in the C language. Note: The original code needs to close the file when the program returns true and false, so that it is only needed once and will not be forgotten. |
Panic, recover |
Package Main Import "FMT" Func Main () { F () Fmt. PRINTLN ("returned normally from F.") } Func f () { Defer func () { If r: = recover(); R! = Nil { Fmt. Println ("Recovered in F", R) } }() Fmt. Println ("calling G.") G (0) Fmt. PRINTLN ("returned normally from G.") } Func g (i int) { If I > 3 { Fmt. Println ("panicking!") Panic (FMT. Sprintf ("%v", I)) } defer FMT. Println ("Defer in G", I) Fmt. Println ("Printing in G", I) G (i + 1) } Returned the following: Calling G. Printing in G 0 Printing in G 1 Printing in G 2 Printing in G 3 panicking! Defer in G 3 Defer in G 2 Defer in G 1 Defer in G 0 Recovered in F 4 Returned normally from F. |
Panic throws the message and jumps out of the function. The recover receives the information and continues processing. |