Home  >  Article  >  Backend Development  >  How are functions defined in Go language?

How are functions defined in Go language?

WBOY
WBOYOriginal
2023-06-10 12:39:071551browse

Go language is a modern programming language that is welcomed and favored by many developers. Its syntax is concise and clear, its execution efficiency is high, and it supports concurrent programming. It is especially suitable for building high-performance and high-concurrency server programs. As a process-oriented programming language, functions play a vital role in it. Next, this article will introduce how functions in the Go language are defined.

  1. Basic definition of function

In the Go language, the definition format of a function is as follows:

func function_name(parameters) (return_type) {
    // 函数体
}

Among them, function_name represents the function name, parameters Represents the parameter list, return_type represents the return value type. It should be noted that the parameter and return value types of Go language functions can be of any type, including basic types, arrays, structures, functions, etc.

  1. Parameter passing methods

There are two methods of parameter passing for Go language functions: value passing and reference passing. In the value passing method, the function receives a copy of the parameter; in the reference passing method, the address of the parameter is passed directly, and changes to the parameters in the function will directly affect the parameters themselves.

2.1. Value passing method

In the value passing method, the parameters of the function are based on a copy of the value rather than the original value. Value-based parameter passing ensures that the value being passed always remains unchanged and therefore cannot be modified. This method is suitable for simple type parameter passing, such as int, float, string and other basic types of parameter passing.

func main() {
    a := 5
    b := 10
    swap(a, b) // a 和 b 传递的是值的副本
    fmt.Println(a, b) // 输出 5 10
}
 
func swap(x, y int) int {
    temp := x
    x = y
    y = temp
    return temp
}

In the above code, the parameters received by the function swap are copies of the values, so the exchange of x and y in swap will not affect the original values ​​​​a and b passed in the call.

2.2. Reference passing method

In the reference passing method, the parameters of the function receive addresses or pointers, and the parameters can be modified directly, thereby changing the original value itself. This method is suitable for parameter passing of reference types such as structures and slices.

type person struct {
    name string
    age int
}
 
func main() {
    p := person{name: "Tom", age: 20}
    modifyPerson(&p) // 传递 p 的地址
    fmt.Println(p) // 输出 {Jerry 30}
}
 
func modifyPerson(p *person) {
    p.name = "Jerry"
    p.age = 30
}

In the above code, the function modifyPerson receives a pointer to the person structure, and can directly modify the structure content corresponding to the parameter. Therefore, a function that modifies the value of p affects the original p variable.

  1. Variable parameters and multiple return values ​​of functions

The Go language supports functions passing a variable number of parameters and supports operations with multiple return values.

3.1. Variable parameters

If the number of parameters of a function is variable, you can use variable parameter syntax when defining the function. The variadic syntax uses ... to indicate that the function accepts a variable number of arguments. The variadic function of Go language can accept any number of parameters, but these parameters must be of the same type.

func sum(nums ...int) int {
    res := 0
    for _, num := range nums {
        res += num
    }
    return res
}
 
func main() {
    fmt.Println(sum(1, 2, 3)) // 输出 6
    fmt.Println(sum(4, 5, 6, 7, 8)) // 输出 30
    fmt.Println(sum()) // 输出 0
}

In the above code, the parameters of function sum use variable parameter syntax, which can accept any number of parameters, then add them and return the result.

3.2. Multiple return values

Function in Go language can have multiple return values. This approach can reduce the number of function calls and improve the readability of the code.

func getNames() (string, string) {
    return "Tom", "Jerry"
}
 
func main() {
    firstName, lastName := getNames()
    fmt.Println(firstName, lastName) // 输出 Tom Jerry
}

In the above code, the function getNames returns two string type values, namely Tom and Jerry. You can use multiple variables to receive the function's return value when you call it.

  1. Anonymous functions and closures

Go language supports anonymous functions and closures. An anonymous function is a function without a name that can be directly defined and used when needed; a closure is an anonymous function that carries state and can call variables in the function, but these variables are only visible inside the closure.

func main() {
    func() {
        fmt.Println("Hello World!")
    }()
 
    add := func(x, y int) int {
        return x + y
    }
    fmt.Println(add(1, 2)) // 输出 3
 
    n := 5
    func() {
        fmt.Println(n+1) // 输出 6
    }()
 
    fmt.Println(n) // 输出 5
}

In the above code, the first anonymous function is defined and called directly in the main function without a name. The second anonymous function is assigned to the variable add and can then be called like a normal function. The third anonymous function refers to the external variable n so that n 1 can be output correctly. Since closures carry state, the value of the external variable n will not be changed after the closure is executed.

In short, functions in the Go language are very important building blocks. Proper use of functions allows us to write efficient, easy-to-use and readable programs. I hope this article has provided you with a preliminary understanding of Go functions. You are welcome to continue to explore the characteristics of Go functions in depth in future development.

The above is the detailed content of How are functions defined in Go language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn