Home  >  Article  >  Backend Development  >  Frequently asked questions about golang functions

Frequently asked questions about golang functions

PHPz
PHPzOriginal
2024-04-26 17:36:011022browse

Here are the answers to common questions about Golang functions: functions do not belong to any type, while methods belong to a specific type. A function pointer is a variable that stores the address of a function and can be used like any other pointer. Functions can return multiple values, returned as tuples. Functions can declare variable-length parameter lists using the ... syntax. Anonymous functions are functions without a name that are used to create one-time use functions.

Frequently asked questions about golang functions

Frequently asked questions about Golang functions

1. The difference between functions and methods

  • Function: A function that does not belong to any type.
  • Method: Function belonging to a specific type.

Code example:

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

// 方法
type Person struct {
    name string
}

func (p Person) greet() string {
    return "Hello, my name is " + p.name
}

2. Function pointer

The function pointer is a variable that stores the function address. They can be used like other pointers to call functions.

Code example:

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

var addFunc = add // 函数指针

func main() {
    result := addFunc(1, 2) // 使用函数指针调用函数
    fmt.Println(result) // 输出: 3
}

3. Return multiple values

The function can use return Statement returns multiple values. The return value is returned as a tuple.

Code example:

func getMinMax(nums []int) (int, int) {
    min := nums[0]
    max := nums[0]
    for _, num := range nums {
        if num < min {
            min = num
        }
        if num > max {
            max = num
        }
    }
    return min, max
}

4. Variable parameter list

Function can be used... Syntax for declaring a variable length parameter list.

Code example:

func sum(nums ...int) int {
    sum := 0
    for _, num := range nums {
        sum += num
    }
    return sum
}

func main() {
    result := sum(1, 2, 3, 4, 5) // 可变参数列表
    fmt.Println(result) // 输出: 15
}

5. Anonymous function

Anonymous function is a function without a name. It is typically used to create one-time use functions.

Code example:

func main() {
    // 创建匿名函数
    add := func(a, b int) int {
        return a + b
    }

    // 使用匿名函数
    result := add(1, 2)
    fmt.Println(result) // 输出: 3
}

The above is the detailed content of Frequently asked questions about golang functions. 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