SoFunction
Updated on 2025-03-06

Detailed explanation of the declaration and use of GO language function (func)

Introduction to GO language functions

GO is a compiled language, so the order of functions is irrelevant. For the sake of easy reading, it is recommended to enter functions.mainWrite it in the front, and the rest of the functions are arranged according to the needs of the function

GO's functionsNesting, overloading and default parameters are not supportedGO's functionsSupport No need to declare variables, variable lengths, multiple return values, anonymity, closures, etc.GO functionsfuncTo declare, with the left brace{Can't start another line

A simple example:

package main
import "fmt"
func main(){
    ("Before calling the function....")
    hello()
    ("After calling the function....")
}
func hello() {
    ("Calling the function...")
}

The output is:

Before calling the function。。。
Calling the function...
After calling the function。。。

GO language function parameters and return value

Parameters: You can pass 0 or more values ​​for your own use

Return: By usingreturnCome back

package main
import "fmt"
func main(){
    a, b, c := 1, 2, 3
    d, e, f := test(a, b, c)
    (a, b, c, d, e, f)
}
func test(a int, b int, c int) (d int, e int, f int) {
    d = a + 3
    e = b + 3
    f = c + 3
    return d, e, f
}

The output is:

1 2 3 4 5 6

The above is a typical multi-parameter pass and multiple return value
An explanation of the example:

  • First, definea,b,cThree variables and assign them to1,2,3
  • Calltest() function, Because we know in advance that this will return three values, we used,e,fReceive the returned value
  • existtestIn the functionfunc test(a int, b int, c int)This section is the received incoming parameter.(d int, e int, f int) {This paragraph defines the returned value
  • existtestIn, rightd,e,fThe variables are respectivelya,b,cAdd 3 on the basis of
  • Print all variables

Pass by value and pass by reference

Pass by value: It is to copy a variable, and the value of the original variable cannot be changed.
Reference pass: It is equivalent to passing by pointer, which can change the original value at the same time, and consume less memory, with only 4 or 8 bytes of consumption

Named return value

In the above example, return the value(d int, e int, f int) {It is named, if you don't want to name it, you can write it(int,int,int){, the returned results are the same, but be careful:

  • When written in the following form, it is serrated within the function, liked,e,fThese variables cannot be used directly, and must be defined before they can be used;
  • Return valuereturn d,e,fIt is necessary to follow the returned value. The former method is to not write the return value, you can directlyreturn
  • When working normally, of course, it is the first way to write it, which will make the code more readable

Return to the blank sign

When multiple values ​​are returned, some of our variables do not want, or are not actually used, we can use_To fill the position, for example, we can write the return of the above example asd,_,f := test(a,b,c), we do not want the intermediate return value, we can discard it in this form

GO language function passes variable length parameters

After the parameterVariable ... typeIn this form, we must judge that this is a variable length parameter

package main
import "fmt"
func main(){
    ke("a", "b", "c", "d", "e")
}
func ke(a string, strs ...string) {
    (a)
    (strs)
    for _, v := range strs {
        (v)
    }
}

The output is:

a
[b c d e]
b
c
d
e

In the above example,strs ...stringmiddle,strsThe actual value is b, c, d, e. This is the simplest example of passing variable length parameters. More evolutionary forms are very similar.

Application of GO language function defer

In GOdeferKeywords are very important, which is equivalent to the destructor in the face relative image, that is, after a certain function is executed, GO will automatically do this;
If the functions in a multi-layer loop are defineddefer, then its execution order is first in and then out;
When a function has a serious error,deferWill be called

package main
import "fmt"
func main(){
    defers("a", "b")
}
func defers(a string, b string) {
    (a)
    defer ("Last call...")
    (b)
}

The output is

a
b
Last call...

This is the simplest test, and of course there are more complex calls. For example, when debugging a program, you can determine which function has a problem. It can be completely based ondeferThe printed content is very fast, and this is left to you to realize.

GO language recursive function

A function calls itself in the body of the function, which we call a recursive function. When making recursive calls, it often fills up memory. This is a very important thing to note. For example, quick sorting is a recursive call.

GO language built-in functions

append -- is used to append elements to arrays and slices, and return the modified arrays and slices.
close -- mainly used to close channel delete -- delete the value corresponding to the key from the map
panic -- Stop regular goroutine (panic and recover: used for error handling)
recover -- Allows the program to define the panic action of the goroutine
image -- Returns the real part of complex (complex, real image: used to create and manipulate complex numbers)
real -- Returns the imaginary part of complex make -- Used to allocate memory and return Type itself (only applied to slice, map, channel)
new -- is used to allocate memory, mainly used to allocate value types, such as int and struct. Returns a pointer to Type
cap -- capacity means capacity, used to return the maximum capacity of a certain type (only used for slices and maps)
copy -- is used to copy and connect slices, return the number of copies len -- to find the length, such as string, array, slice, map, channel, return the length
print, println -- The underlying printing function, it is recommended to use the fmt package in the deployment environment

This article focuses on the declaration and use of GO functions (func). For more information about GO language functions, please see the relevant links below