Overview
existPrevious SectionIn the content of , we introduce Go's pointers, including: using pointers, null pointers, pointers arrays, pointers to pointers, etc. In this section, we will introduce Go's functions. Functions allow developers to organize relevant code together and name it so that they can be called elsewhere. In Go, a function is a reusable block of code that performs specific operations.
Function definition
The basic format of function definition is as follows:
func funcName(parameter1 type, parameter2 type) returnType { // Function body // Some operations can be performed here // When the function ends, one or more values can be returned return value1, value2, ... }
The following details of each element in the above format.
- func: keyword, used to declare a function.
- funcName: The name of the function, which is used to identify the unique identifier of the function.
- parameter1, parameter2: The parameter list of the function, each parameter consists of the parameter name and parameter type. Parameters are optional, that is, the function may contain no parameters.
- type: The data type of the parameter can be any valid Go data type, such as: integers, floating point numbers, strings, etc.
- returnType: The type of the function returns the value, which is optional. If the function does not return any value, the return type is void or (); if the function returns a value, the data type of the value will be specified as the return type; if the function returns multiple values, the data types of these values need to be given in turn.
- return value1, value2, ...: The function returns statement, which specifies the value returned by the function. It can return a single value or multiple values. If no value needs to be returned, the return statement can be omitted.
In the following example code, we define three functions. The first function MyPrint has no return value, the second function Add has one return value, and the third function Process has two return values.
package main import "fmt" // No return valuefunc MyPrint(text string) { (text) } // A return valuefunc Add(a int, b int) int { return a + b } // Multiple return valuesfunc Process(data int) (int, string) { if data >= 100 { return 0, "OK" } return -1, "Invalid" } func main() { MyPrint("Hello CSDN") sum := Add(100, 200) // Output: 300 (sum) result, info := Process(188) // Output: 0 OK (result, info) }
Function declaration
In Go language, function declaration and function definition are two related concepts, but they still have some differences.
Function definitions are used to write a function in a complete manner, including: function name, parameter list, return type, and function body. It implements the specific logic of the function, and the function definition should only be once in the program.
Function declarations are used to tell the compiler the name, parameter list, and return type of the function so that the function can be used elsewhere. It includes function names, parameter lists, and return types, but does not have function bodies. The function declaration tells the compiler: "There is a function like this, and it can be called like this".
Unlike C/C++ language, Go does not distinguish between header files and implementation files. Functions, variables, structures, etc. in Go language can be defined and implemented in the same file, or they can be defined and implemented in different files. When writing source code, you can place the declaration and definition of the function in the same file, or you can place them in different files separately.
Function Calls
When calling a function, parameters can be passed in two ways: one is value passing and the other is reference passing. Value passing refers to copying a copy of the actual parameters into the function when calling a function. In this way, if the parameters are modified in the function, the actual parameters will not be affected. Reference passing refers to passing the address of the actual parameter into the function when calling a function. In this way, the modifications made to the parameters in the function will affect the actual parameters. By default, Go uses value passing, that is, the actual parameters will not be affected during the call.
In the following example code, we declare and define two functions. The Process1 function uses the method of passing value, so the number remains unchanged after being called. The Process2 function uses reference passing method, so the number value will be changed to 166 after calling.
package main import "fmt" // Value passfunc Process1(number int) { number += 100 } // Reference passfunc Process2(pNumber *int) { *pNumber += 100 } func main() { number := 66 Process1(number); // Output: 66 (number) Process2(&number); // Output: 166 (number) }
In Go, multiple return values can be used to return multiple results. These return values can be of different data types and can be packaged together into a tuple. When a function has multiple return values, we can use placeholders to ignore unwanted return values, and placeholders are represented by underscores (_).
package main import "fmt" func Calc(x, y int) (int, int) { return x + y, x * x + y * y } func main() { // Multiple return values, assign values in sequence sum, square := Calc(6, 8) // Output: 14 100 (sum, square) // Use placeholders, ignore the first return value _, square2 := Calc(6, 8) // Output: 100 (square2) }
Variable parameter functions
A variadic parameter function is a function that can accept variable number of parameters. By declaring variable parameters using ellipsis..., the function can accept any number of parameters of the same type. When a mutable parameter function is called, the parameters passed to the function are passed to the function as a slice. Inside the function, slices can be used to access and manipulate these parameters.
In the following example code, the sum function is a mutable parameter function that accepts one or more parameters of type int. In the function definition, the parameter name number after... means that this is a mutable parameter. In the function body, you can use numbers slices to access all parameters passed to the function. By traversing the slice, the sum of all parameters can be calculated and the result can be returned. In main main function, we call the sum function and pass multiple integer parameters. These integers are automatically packaged into a slice and then passed to the sum function.
package main import "fmt" func sum(numbers ...int) int { total := 0 for _, value := range numbers { total += value } return total } func main() { // Output: 300 (sum(100, 200)) // Output: 600 (sum(100, 200, 300)) }
Anonymous functions
Anonymous functions, also known as closures. Anonymous functions are functions without a declared name and can be used directly in the code. In the following example code, we define an anonymous function and assign it to the variable add. Then, we call the add function and assign the result to the variable result. Finally, we output the value of result.
package main import "fmt" func main() { // Define anonymous functions add := func(a, b int) int { return a + b } result := add(66, 88) // Output: 154 (result) }
Anonymous functions can access variables outside of them, which is called closure characteristics. In the following example code, we define a variable called origin and initialize it to 1000. We then define an anonymous function and assign it to the add variable. In anonymous functions, we access the externally defined origin variable. Finally, we call the anonymous function through the add variable.
package main import "fmt" func main() { origin := 1000 // Anonymous functions can access external variables add := func(a, b int) int { return a + b + origin } result := add(66, 88) // Output: 1154 (result) }
Recursive functions
In Go language, recursive functions can be used, that is, a function calls itself inside itself. Recursive functions are usually used to solve problems that require repeated execution of the same operations, such as: calculating factorials, Fibonacci sequences, etc. It should be noted that recursive functions must have a termination condition. Otherwise, it will continue infinitely recursion, causing stack overflow or even program crash.
In the following example code, we define a recursive function called factorial. It takes an integer n as an argument and returns a factorial of n. If n is equal to 0, return 1; otherwise, return the result of n multiplying factorial(n-1). In the main function, we call the factorial function and print the result out.
package main import "fmt" func factorial(n int) int { if n == 0 { return 1 } return n * factorial(n - 1) } func main() { num := 5 result := factorial(num) // Output: 5! = 120 ("%d! = %d\n", num, result) }
Advanced functions
Higher-order functions are an important feature of functions in Go language. They allow functions to be passed as parameters to other functions, or as return values of functions. Advanced-order functions are very useful in Go languages, enabling more flexible and reusable code. By passing functions as arguments to other functions, we can implement combination and pipeline functions, thereby simplifying code and improving readability.
In the following example code, we define a higher-order function called ApplyFunc. It accepts a function as parameter f and calls the function with the given values x and y. We then define two simple functions Add and Sub for adding and subtracting the two parameters passed. Finally, we pass the Add function and the Sub function as parameters to the ApplyFunc function and assign the execution result of the function to the variable result.
package main import "fmt" // Define a higher-order function and accept a function as a parameterfunc ApplyFunc(f func(int, int) int, x int, y int) int { return f(x, y) } func Add(x int, y int) int { return x + y } func Sub(x int, y int) int { return x - y } func main() { result := ApplyFunc(Add, 99, 66) // Output result: 165 (result) result = ApplyFunc(Sub, 99, 66) // Output result: 33 (result) }
This is the article about Go function usage (function definition, function declaration, function call, etc.). For more relevant Go function usage content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!