SoFunction
Updated on 2025-03-05

Detailed explanation of how to use functions in Golang

function

Function call: When calling a function, you need to pass the parameters required in the function definition and receive the return value as needed.

Anonymous functions: Anonymous functions have no function name and can be directly defined and called. Commonly used as closures inside functions.

Closure: A closure refers to a function defined internally by a function. It can access variables of external functions and bind these variables to the function to form a closed environment.

Variable parameters: Use ... to represent variable parameters. Variable parameters must be placed at the end of the function parameter list, and there can only be one.

Functions as parameters: Functions can be passed as parameters to other functions, and this kind of function is called a higher-order function. Commonly used in functional programming.

Functions are returned values: Functions can also be returned values, and this kind of function is called closures. Commonly used to implement functions similar to decorators or sections.

Function Features

1. The function can have multiple return values.

2. Functions can be passed as parameters to other functions.

3. Anonymous functions can be defined.

4. Support closures.

5. Functions can have multiple parameters and multiple return values.

6. Variable parameters can be used.

Use of functions

Function definition

The definition of functions in Go uses the func keyword, and its basic syntax format is as follows:

func Function name(Parameter list) (Return to the value list) {
    Function body
}

in:

  • Function name represents the name of the function, follows the naming rules of identifiers, and adopts camel nomenclature.
  • Parameter list represents the input parameters of the function, separated by commas, each parameter consists of parameter name and parameter type, such as param1 type1, param2 type2.
  • Return value list Represents the return value of the function, enclosed in brackets, and can be multiple return values, such as (type1, type2).
  • Function body represents the specific implementation logic of the function.

For example, here is a function that calculates the sum of two integers:

func Add(x, y int) int {
    return x + y
}

The above function is namedAdd, there are two parametersxandy, all types areint, the return value type isint, the function body is implemented asxandyAdd and return the result.

Function parameters

Functions can have multiple parameters, and the type of the parameter is placed after the parameter name. If the types of two or more consecutive parameters are the same, the type can be omitted, for example:

func swap(x, y string) (string, string) {
   return y, x
}

The return value of the function

Functions can return multiple values ​​enclosed in brackets and separated by commas. For example:

func sum(a int, b int) (int, int) {
   return a+b, a-b
}

Can be used:=The assignment statement calls the function and automatically infers the return value type:

a, b := sum(1, 2)

The parameters of the function are value passed. When the function is called, a copy of the actual parameter is passed.

Variable scope of function

The scope of the variable declared in the function is inside the function and is invisible outside the function. If global variables are used in the function, they can be used directly in the function.

Recursive call to functions

Functions can be called recursively, and recursive calls must have a termination condition. For example:

func factorial(n uint64) (result uint64) {
   if (n > 0) {
      result = n * factorial(n-1)
      return result
   }
   return 1
}

Variable parameters of functions

Variable parameters of a function are a very useful feature and can accept any number of parameters. Add an ellipsis before the last parameter in the parameter list...Just:

func sum(numbers ...int) int {
   total := 0
   for _, number := range numbers {
      total += number
   }
   return total
}

Function closure

A closure of a function refers to a function that can access variables in its external scope. For example:

func main() {
   nextInt := intSeq()
 
   (nextInt())
   (nextInt())
   (nextInt())
 
   newInts := intSeq()
   (newInts())
}
 
func intSeq() func() int {
   i := 0
   return func() int {
      i += 1
      return i
   }
}

The above code outputs:

1
2
3
1

The defer statement of the function

In Go language, the defer statement of a function can perform some cleaning work when the function returns, such as closing files, unlocking resources, etc. The defer statement can be inserted anywhere in the function, and multiple defer statements can be defined. When the function is executed, each defer statement will be pushed into a stack, waiting for the function to be executed in reverse order.

func main() {
    defer ("deferred")
    ("regular")
}

This program outputs:

regular
deferred

In this example, when the main function is executed into the defer statement, "deferred" is pushed into a stack. Then the program continues to execute and outputs "regular". When the function returns, the defer statement in the stack is executed in reverse order, and finally the output is "deferred".

In addition to being used to clean up resources, the defer statement can also be used to record the execution time of the function. Here is an example:

func timeTrack(start , name string) {
    elapsed := (start)
    ("%s took %s", name, elapsed)
}
 
func myFunc() {
    defer timeTrack((), "myFunc")
    // The actual code of the function}

In this example, the timeTrack function is used to record the execution time of the function. In myFunc function, the defer statement is used to call the timeTrack function and pass the current time and function name as parameters. When the myFunc function returns, the timeTrack function is executed, and the execution time of the function is output.

Notice

  • Naming specification: Function names should be meaningful, and the camel nomenclature is adopted. The first letter is capitalized to indicate that the function is public, and the first letter is lowercase to indicate that the function is private.
  • Parameter passing: The parameter passing of Go language function is passed by value. If you need to modify the passed parameters, you can pass a pointer.
  • Return value: Go language function can return multiple values, define the variable name of the return value, or omit the variable name, but it is recommended to write the variable name to facilitate code reading.
  • Error handling: Go language functions generally return an error value to indicate whether the function execution is successful, and error handling is required in the place where the function is called.
  • Function variables: In Go language, functions can also be used as variables, and functions can be assigned to variables or passed as parameters to other functions.
  • defer statement: The defer statement is used to perform some cleaning operations before the function returns, such as closing the file, releasing the lock, etc. The execution order of the defer statement is "Last in first out".

The above is a detailed explanation of the usage methods of functions in Golang. For more information on the use of Golang functions, please pay attention to my other related articles!