Technology Sharing

【Go - 5 common types of function usage】

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

function

Function byfuncKeyword definition, followed by function name, parameter list, and return type. The syntax is as follows:

func functionName(parameters) returnType {
    // 函数体
}
  • 1
  • 2
  • 3

Example

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

func swap(x, y string) (string, string) {
    return y, x
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Variable parameter function

func sum(nums ...int) int {
    total := 0
    for _, num := range nums {
        total += num
    }
    return total
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Anonymous functions

	s := (func () string {
		return "anonymous-function"
	})()
	fmt.Println(s)
  • 1
  • 2
  • 3
  • 4

**Higher-order functions, **functions as parameters and return values

Functions can also be passed in as parameters or returned as values.

// 函数作为参数
func compute(fn func(float64, float64) float64) float64 {
    return fn(3, 4)
}

// 函数作为返回值
func getComputeFunc() func(int, int) int  {
   return func(x, y int) int {
       return x + y
   }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Closure


func intSeq() func() int {
    i := 0
    return func() int {
        i++
        return i
    }
}

// 调用
func main() {
    incfunc := intSeq()
    fmt.Println(incfunc())
    fmt.Println(incfunc())
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Closure is essentially an extension of scope.
For example, if i in intSeq is not referenced anywhere else, it will be garbage collected. However, since there is a reference to it in incfunc, it cannot be recycled, its life cycle becomes longer, and its scope is extended.