Thoroughly understand the functions in Golang

A function in Golang is a set of code blocks used to perform a specific task. With the help of functions, the code can be modularized. A complex function can be broken down into small chunks of code, which can then be written by different people at different times.

function definition

A function definition in Golang begins with the keyword func, followed by the function name, parameter list, and return value list. The basic syntax of a function definition is as follows:

func functionName(parameterList) (returnParameterList) {  
    // 函数体  
}

The specific meaning is as follows:

  • functionName: function name, used to identify the function.
  • parameterList: A list of parameters accepted by the function, separated by commas. If no arguments are entered, empty parentheses are used.
  • returnParameterList: The parameter list returned by the function, separated by commas. If there is no return parameter, just leave it blank.
  • Function body: Contains the code block that implements the functions of the function.

The following is a sample code for a simple function definition:

func add(a, b int) int {  
    return a + b  
}

A function can accept zero or more input parameters. These parameters are specified when the function is defined and passed when the function is called. A simple example is as follows:

// 接受一个字符串类型参数
func printString(s string) {  
    fmt.Println(s)  
}  
  
// 接受两个整数类型参数
func add(a, b int) int {  
    return a + b  
}  
  
// 接受一个浮点数和一个整数类型参数
func divide(f float64, i int) float64 {  
    return f / float64(i)  
}

When calling a function, the actual parameters passed to the function must match the number and types of parameters defined by the function. For example, the sample code for calling the add function is as follows:

result := add(2, 3) // 调用add函数,传入两个整数类型参数2和3  
fmt.Println(result) // 输出5

Golang also supports variadic parameters, which means that a function can accept a variable number of parameters. The type and number of these parameters can be determined at runtime. Varargs are denoted by an ellipsis (...) in the parameter list of a function definition. The sample code is as follows:

package main  
  
import "fmt"  
  
func println(args ...interface{}) {  
    for _, arg := range args {  
        fmt.Println(arg)  
    }  
}  
  
func main() {  
    println("Hello, ", "World!")  
    println("路多辛的博客", 42, true)  
}

The println function takes a variable parameter args, and in the function body, loops through args and prints the value of each parameter. Then call the println function twice in the main function, passing a different number of arguments each time.

A function can return zero or more parameters, which are specified when the function is defined and received using variables when the function is called. A simple example is as follows:

// 返回一个字符串
func greet(name string) string {  
    return "Hello, " + name + "!"  
}  
  
// 返回两个整数
func add(a, b int) (int, int) {  
    return a + b, a - b  
}  
  
// 返回一个浮点数和一个整数
func multiply(f float64, i int) (float64, int) {  
    return f * float64(i), i  
}

When a function is called, variables can be used to receive the return parameters of the function. For example:

message := greet("路多辛") // 调用greet函数,接收返回的字符串参数 message  
fmt.Println(message)     // 输出 "Hello, 路多辛!"

main function

The main function is a special function that is the entry point of the program. The main function must be defined in the main package, does not accept any parameters, and has no return value. Each program has and can only have one main function. A simple example is as follows:

package main  
  
import "fmt"  
  
func main() {  
    fmt.Println("路多辛的所思所想!")  
}

init function

The init function is also a special function. Like the main function, it is also a special-purpose function reserved for the Go compiler. It does not accept any parameters and has no return value. But multiple init functions can be created in a program, and even multiple init functions can be created in each file.

The init function will be executed before any code block in the package is executed. The execution order of the init function is as follows:

If the init functions in multiple packages are to be executed, they will first be executed in the order of the fields of the package name (except for the main package, the init function in the main package will wait for the init functions in all other packages to execute before executing), the init functions in the same package are executed in the dictionary order of the file names, and the init functions in the same file are executed in the order of creation.

Closures (anonymous functions)

For an explanation of anonymous functions and closures, please refer to the previous article "Detailed Explanation of Closures in Golang".

recursive function

Functions that call themselves are called recursive functions, and functions that call each other are called mutually recursive functions. A typical feature of a recursive function is that when calling itself recursively, it must have a termination condition to prevent stack overflow due to infinite recursion. A simple example is as follows:

func fibonacci(num int) int {
	if num < 2 {
		return num
	}
	return fibonacci(num-1) + fibonacci(num-2)
}

summary

In addition to the features introduced above, functions in Golang also have the following features:

  • Function overloading is not supported
  • Function names in the same package cannot be repeated (except the init function)
  • Does not support default parameters

Guess you like

Origin blog.csdn.net/luduoyuan/article/details/131713562