Home > Backend Development > Golang > Common usage of Golang functions

Common usage of Golang functions

PHPz
Release: 2023-04-25 15:46:31
Original
682 people have browsed it

Go is a new programming language that is efficient and easy to use. Its function usage is also very flexible. This article will introduce in detail the common usage and precautions of Golang functions.

1. Declaration of function

When declaring a function in Go language, you need to specify the function name, parameters and return value. The basic format of the function is as follows:

func 函数名 (参数1, 参数2, ...) (返回值1, 返回值2, ...) {
    // 函数体
}
Copy after login

Among them, the function name follows the identifier naming convention. Function parameters can be of any type, or they can have no parameters. The return value can be of any type, or there can be no return value.

For example, the following is a simple function declaration:

func add(x int, y int) int {
    return x + y
}
Copy after login

In this function, we declare a function named add, which has two integer types The parameters x and y are, and the return value is their sum.

2. Multiple return value functions

Go language supports multiple return value functions. For example:

func divmod(a, b int) (int, int) {
    return a / b, a % b
}
Copy after login

In this function, we declare two integer type parameters a and b, and return two integer type values ​​respectively. is the result of division and modulo operations.

3. Functions as parameters

In the Go language, functions can be passed to other functions as parameters. For example:

func apply(nums []int, f func(int) int) []int {
    result := []int{}
    for _, v := range nums {
        result = append(result, f(v))
    }
    return result
}
Copy after login

In this function, we declare a function named apply, which has two parameters, one is a slice of integer type nums, The other is a function f, which takes an integer parameter as input and returns an integer result. Function apply passes each element in slice nums to function f, and returns the result of each function execution stored in a new slice.

For example:

func square(x int) int {
    return x * x
}

result := apply([]int{1, 2, 3, 4}, square) // [1, 4, 9, 16]
Copy after login

In this example, we define a function square that squares an integer and use the apply function to Each integer in slice {1, 2, 3, 4} is applied to the function square, resulting in a new slice [1, 4, 9, 16 ]as a result.

4. Nesting functions within functions

In the Go language, functions can be declared and defined in other functions. For example:

func outer(x, y int) int {
    square := func(x int) int {
        return x * x
    }

    return square(x) + square(y)
}
Copy after login

In this function, we define a function named outer, which has two integer type parameters x and y. Function outer declares and defines an anonymous function square that squares an integer. Then, function outer passes both parameters x and y to function square, and adds the results back.

5. Functions as return values

In Go language, functions can be used as return values. For example:

func adder() func(int) int {
    sum := 0
    return func(x int) int {
        sum += x
        return sum
    }
}
Copy after login

In this function, we define a function named adder which does not accept any parameters and returns a function. The returned function also accepts an argument of type integer and returns a result of type integer. Inside the function adder, we define an integer type variable sum and return an anonymous function that adds the parameter x to sum , and returns the new value of sum.

For example:

add := adder() // 返回一个函数
fmt.Println(add(1)) // 输出 1
fmt.Println(add(2)) // 输出 3
fmt.Println(add(3)) // 输出 6
Copy after login

In this example, we first call the adder() function to get a new function add, and then use addThe function is passed three times, each time passing an integer type value, and finally 1 2 3=6 is obtained.

6. defer statement

In the Go language, we can use the defer statement to perform some cleanup work after the function execution is completed. For example:

func f() {
    defer fmt.Println("Done.")
    fmt.Println("Working.")
}

f() // 输出 "Working." 和 "Done."
Copy after login

In this example, we define a function named f, which contains two statements. The first statement prints "Working." and the second statement prints "Done." using the defer keyword. Due to the presence of the defer keyword, the second statement will be output after the function execution is completed.

In addition, the defer statement has some more advanced uses, such as using it in file reading and writing operations, which can ensure that the file handle is closed correctly at the end of function execution.

Summary

This article introduces the common usage and precautions of Golang functions, including function declaration, multiple return value functions, functions as parameters, nested functions in functions, and functions as return values and defer statement. Using these tips, you can write more concise, elegant, and efficient Go programs.

The above is the detailed content of Common usage of Golang functions. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template