SoFunction
Updated on 2025-03-04

This article will help you get familiar with the use of functions in Go language

function

The English word of function isFunction, there is stillFunctionMeaning. In Go language, functions are blocks of code that implement a specific function. Functions represent a function that can be used multiple times in the same place or in different places. Therefore, using functions can improve the reusability of the code and reduce the redundancy of the code.

Declaration of functions

Learn what parts of the declaration of a function are through the case:

Define a function to implement the function of adding two numbers, and return the result after adding.

func Add(num1 int, num2 int) int {
    var sum int
    sum += num1
    sum += num2
    return sum
}

Through the case, we can find that the declaration of the function has5part:

1. Keywords

The keyword of the function isfunc, declare the function must befuncKeywords begin.

2. Function name

GoIt is recommended to use camel naming. Like the naming rules of variables, function names with uppercase letters can be accessed outside the package, while lowercase letters can only be accessed inside the package.

3. Parameter list

The variables used in the function body are declared in the parameter list. The parameter list is behind the function name, wrapped in brackets, and multiple parameters are separated by commas.

4. Return value list

The return value is a result after the function is executed. The above code has only one return value. If there are multiple return values, it needs to be wrapped in brackets, and the return values ​​are separated by commas.

In rare cases, we will declare the name of the return value such asfunc Add(num1 int, num2 int) sum int {}, in most cases, the name of the return value is not required.

5. Function body

The function body is in the braces, which stores the specific implementation of the function. The function's first3The4Parts are optional, that is, a function can have no parameters and return values.

Go functions support variable-length parameters

In the above case, the function implemented is to sum two numbers. If we need to sum multiple numbers but do not know the specific number, how should we declare the parameters of the function? At this time, variable-length parameters can be declared to receive multiple parameters.

func main() {
    sum := Add(1, 2, 3, 4)
    println(sum) // 10
}

func Add(nums ...int) int {
    var sum int
    for _, num := range nums {
	sum += num
    }
    return sum
}

Variable length parameters can receive uncertain actual parameters as formal parameters, and declare variable length parameters need to be added in front of the type..... The variable parameter is actually a slice that can be passedfor-rangeGo to operate.

Anonymous functions

Normally, if a function is used only once, we can define it as an anonymous function.

func main() {
    // Define anonymous functions and call them directly    result := func(num1, num2 int) int {
	return num1 + num2
    }(1, 2)
    println(result)
    // 2. Assign anonymous function to a variable and call it by the variable    resultFunc := func(num1, num2 int) int {
	return num1 + num2
    }
    println(resultFunc(1, 2))
}

When declaring a function, a function that does not specify the function name is called anonymous function. Anonymous functions can be called directly or by assigning values ​​to variables.

Closure

A closure is a whole combination of a function and its related reference environment.

import "fmt"

// The return value is an anonymous functionfunc getSum() func(int) int {
    var sum int = 0
    // Anonymous functions    result := func(num int) int {
	sum += num
	return sum
    }
    return result
}

func main() {
    f := getSum()
    (f(1)) // 1
    (f(2)) // 3
}
  • The essence of a closure is an anonymous function, and the function that defines it is used in anonymous functions (getSum) variables insidesum, it forms a closure.
  • From the above code, we can see that the variables referenced in anonymous functions aresumWill be saved in memory all the time.

init function

EachgoAll files can contain oneinitFunction, it is an initialization function, used to perform initialization operations.

var print = getNum()

func getNum() int {
    println("Initialize variables")
    return 1
}

func main() {
    println("main...")
}

func init() {
    println("init...")
}

Execution results:

Initialize variables
init...
main...

  • According to the execution results, they are executed in the order of: global variables →initFunction →mainfunction.
  • MultiplegoAll files are availableinitWhen performing functions, the execution order is: first execute the imported moduleinitfunction, then execute theinitfunction.

Detailed explanation of function parameters

Formal and actual parameters

Where the function is declared, the parameters in the parameter list are called formal parameters, referred to as formal parameters, and the parameters passed when the function is called are called actual parameters, referred to as actual parameters. Give an example:

func main() {
    sum := Add(1, 2)
    println(sum) // 3
}
func Add(num1 int, num2 int) int {
    var sum int
    sum += num1
    sum += num2
    return sum
}

AddThe following parameters are called formal parameters, andmainIn the method,1and2It is called a real argument.

Value pass

When the basic data type and array are used as real parameters, the default is to pressValue pass, that is, copy the value and modify their values ​​within the function, the original value will not change. Give an example:

func main() {
    num1, num2 := 1, 2
    Swap(1, 2)
    ("Main function prints in body: num1: %d, num2: %d", num1, num2)
}

func Swap(num1 int, num2 int) {
    num2, num1 = num1, num2
    ("Swap function prints in body: num1: %d, num2: %d\n", num1, num2)
}

Execution results:

Swap function prints in body: num1: 2, num2: 1
main function prints in body: num1: 1, num2: 2

existSwapIn the function,num1andnum2The values ​​ofmainIn the function,num1andnum2The value of 1000 has not changed.

func main() {
    nums := [3]int{0, 1, 2}
    Swap(nums)
    ("main function prints in body: nums: ", nums)
}

func Swap(nums [3]int) {
    nums[0] = 1
    ("Swap function prints in body: nums: ", nums)
}

The array is also passed, and the value of the array is modified within the function, and the value of the original array will not change. The previous article introduced the pointer and pointed out that it was passed*Operators can modify the value of the variable pointed to by the pointer. Therefore, if we want to change the value of the parameter passed outside within the function, the formal parameter type is specified as the pointer type when the function is declared.

func main() {
    num1, num2 := 1, 2
    Swap(&num1, &num2)
    ("Main function prints in body: num1: %d, num2: %d", num1, num2)
}

func Swap(num1 *int, num2 *int) {
    *num2, *num1 = *num1, *num2
    ("Swap function prints in body: num1: %d, num2: %d\n", *num1, *num2)
}

Execution results:

Swap function prints in body: num1: 2, num2: 1
main function prints in body: num1: 2, num2: 1

From the results, we can see that using pointer variables as formal parameters can change the value of external parameters in the function.

Function is a data type

existGoIn it, a function is a data type, so there are many uses of functions, such as creating a function variable, using a function as a formal parameter, using a function as a return value, etc.

Create function variables

func main() {
    // Create function variables    hl := Hello
    ("%T\n", hl) // func(string)
    hl("cmy")
}

func Hello(name string) {
    ("Hello %s", name)
}

Create a function variablehl,PrinthlType →func(string),passhlVariable calls function.

Formal parameters as functions

import "fmt"

func main() {
    Print("cmy", Hello)
}

func Hello(name string) {
    ("Hello %s", name)
}

func Print(name string, f func(string)) {
    f(name)
}

Define functionsPrint, declare two parameters, one parameter isname,forstringType, another parameter isf, is the function type. IncomingcmyandHelloFunction, byPrintFunctions to executeHellofunction.

Return value as function

import "fmt"

func main() {
    f := Print()
    f()
}

func Print() func() {
    return func() {
	("Hello,World!")
    }
}

passPrintThe function returns an anonymous function function, and the function of this anonymous function is the outputHello,World!,usefThe variable receives this function and calls it.

Customize types based on functions

type AddHandleFunc func(num1, num2 int) int

func main() {
    sum := GetSum(1, 2, Add)
    println(sum)
}

func Add(num1, num2 int) int {
    return num1 + num2
}

func GetSum(num1, num2 int, handleFunc AddHandleFunc) int {
    return handleFunc(num1, num2)
}

Based on functionsfunc(num1, num2 int) intCustomize a typeAddHandleFunc, declare it asGetSumand then callGetSumWhen, becauseAddFunctions andAddHandleFuncis equivalent, soAddPass it in as a practical participle.

summary

This article introduces the declaration of the function and understands the 5 parts of its composition based on one case. Then, some of its features are introduced, such as supporting variable-length parameters and passing parameters, the actual parameters areValue passetc. Finally, based on the characteristics of the function being a data type in Go, some of its special uses are explained.

The above is a detailed article that will help you get familiar with the use of functions in Go. For more information about Go functions, please follow my other related articles!