SoFunction
Updated on 2025-03-04

Go language function learning tutorial

This article describes the basic usage of Go language functions. Share it for your reference, as follows:

Here I want to talk about the difference between Go functions and some other languages

1 The function format is different

Copy the codeThe code is as follows:
func GetMsg(i int) (r string) {
    (i)
    r = "hi"
    return r
}

func means this is a function

GetMsg is the function name

(i int) function receives an int parameter

(r string) function returns a string type return value

2 Functions can return multiple return values

This is different from c and php, and it is the same as lua

Copy the codeThe code is as follows:
func GetMsg(i int) (r string, err string) {
    (i)
    r = "hi"
    err = "no err"
    return r,err
}

3 Defer usage

Defer means "call when the function exits", especially when reading and writing operations on files, you need to call the close operation after opening, and use defer to the close operation to use the close operation

Copy the codeThe code is as follows:
func ReadFile(filePath string)(){
    (filePath)
    defer ()
    if true {
        ()
    } else {
        return false
    }
}

The meaning of writing this means not to call close immediately afterwards, and to call() when return false. This effectively avoids memory leakage in C language.

4 Hard to understand: panic, recover and defer

The role of defer is explained clearly before.

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

The following example:

Copy the codeThe code is as follows:
package main
import "fmt"
func main() {
    f()
    ("Returned normally from f.")
}
func f() {
    defer func() {
        if r := recover(); r != nil {
            ("Recovered in f", r)
        }
    }()
    ("Calling g.")
    g(0)
    ("Returned normally from g.")
}
func g(i int) {
    if i > 3 {
        ("Panicking!")
        panic(("%v", i))
    }
    defer ("Defer in g", i)
    ("Printing in g", i)
    g(i + 1)
}

Returned:

Copy the codeThe code is as follows:
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 received the information and continued to process it.

After understanding this example, you can basically master Recover and Panic

I hope this article will be helpful to everyone's Go language programming.