Home >Backend Development >Golang >Introduction to go language functions

Introduction to go language functions

尚
forward
2019-11-30 14:52:232240browse

Introduction to go language functions

The differences between Go functions and some other languages

1. Different function formats

func GetMsg(i int) (r string) {
    fmt.Println(i)
    r = "hi"
    return r
 
}

func indicates that this is Function

GetMsg is the function name

(i int) The function receives an int parameter

(r string) The function returns a string type return value

2. Functions can return multiple return values

This is different from c and php, but the same as 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 "called when the function exits", especially when reading and writing files, you need to call the close operation after open, and use defer

for the close operation. What
func ReadFile(filePath string)(){
    file.Open(filePath)
    defer file.Close()
     
    if true {
        file.Read()
    } else {
        return false
    }
 
}

means is not to call close immediately after file.Open, but to call file.Close() when return false. This effectively avoids the memory leak problem in C language.

4. The more difficult to understand: panic, recover and defer

defer: Recommended: go defer (go delay function) introduction

Panic and Recover we regard them as throw and catch in other languages

The following example:

ackage 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 throw Information is output and the function exits. Recover receives the information and continues processing.

Recommended: go language tutorial

The above is the detailed content of Introduction to go language functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete