Learn the Go language functions tutorial
- 2020-06-01 09:58:05
- OfStack
This article illustrates the basic usage of Go language functions. I will share it with you for your reference as follows:
So I'm going to say 1 is the Go function is different from 1 in some other language
1 function format is different
func GetMsg(i int) (r string) {
fmt.Println(i)
r = "hi"
return r
}
func says that this is a function
GetMsg is the function name
The (i int) function receives one int parameter
The (r string) function returns a value of type string
The 2 function can return multiple return values
This is different from c, php, and lua
func GetMsg(i int) (r string, err string) {
fmt.Println(i)
r = "hi"
err = "no err"
return r,err
}
3 use of defer
defer means "call when a function exits", especially when reading or writing to a file. close is called after open, and close is used by defer
func ReadFile(filePath string)(){
file.Open(filePath)
defer file.Close()
if true {
file.Read()
} else {
return false
}
}
This means that instead of calling close immediately after file.Open, file.Close () is called when return false is called. This effectively avoids memory leaks in the C language.
4. Difficult to understand: panic, recover and defer
So defer is very clear.
Panic and Recover, we think of them as throw and catch in other languages
Here's an example:
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:
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 information and jumps out of the function. Recover receives the information and continues to process it.
If you understand this example, you will have a basic understanding of Recover and Panic
I hope this article has been helpful to you in the programming of Go language.