golang function nested function parameter passing

WBOY
Release: 2024-04-22 21:21:01
Original
1135 people have browsed it

Go functions can be nested, and embedded functions can access external function variables. Parameter passing methods include: passing by value (copying the value) and passing by reference (passing the address). Nested functions and parameter passing are used in practical applications, such as calculating the average of an array and modifying external variables by passing by reference to achieve flexible data processing.

golang function nested function parameter passing

Go function nested function parameter passing

Functions in Go can be nested, which means that a function can be defined in inside another function. Nested functions can access variables of outer functions, but not vice versa.

Syntax

The syntax of nested functions is as follows:

func outerFunction(args ...) {
  func innerFunction(args ...) {
    // 访问外部函数的变量
  }
}
Copy after login

Parameter passing

When nested When a function is called, its arguments can be passed to external functions. Parameters can be passed in the following ways:

  • Pass by value: Parameter values ​​are copied and passed to the nested function.
  • Pass by reference: The address of the parameter is passed to the nested function.

Example of passing by value:

func outerFunction(x int) {
  func innerFunction(y int) {
    fmt.Println(x + y) // 输出 x + y
  }

  innerFunction(10)
}

func main() {
  outerFunction(5) // 输出 15
}
Copy after login

Example of passing by reference:

func outerFunction(x *int) {
  func innerFunction(y *int) {
    *y += *x // 更改外部函数的变量 x
  }

  innerFunction(x)
}

func main() {
  x := 5
  outerFunction(&x)
  fmt.Println(x) // 输出 10
}
Copy after login

Practical case

The following is a practical case using nested functions and passing by reference:

func calculateAverage(data []int) {
  sum := 0

  // 内嵌函数用于计算数组中的每个元素的总和
  func sumArray(data []int) {
    for _, v := range data {
      sum += v
    }
  }

  sumArray(data)
  return float64(sum) / float64(len(data))
}

func main() {
  data := []int{1, 2, 3, 4, 5}
  fmt.Println(calculateAverage(data)) // 输出 3.0
}
Copy after login

The above is the detailed content of golang function nested function parameter passing. 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