GO语言函数值传递与闭包

函数值传递
函数也是值。他们可以像其他值一样传递,比如,函数值可以作为函数的参数或者返回值。
package main

import (
	"fmt"
	"math"
)

func compute(fn func(float64, float64) float64) float64 {
	return fn(3, 4)
}

func main() {
	hypot := func(x, y float64) float64 {
		return math.Sqrt(x*x + y*y)
	}
	fmt.Println(hypot(5, 12))   //调用hypot函数,输出13

	fmt.Println(compute(hypot))  //将hypot函数作为compute函数的参数,使用3,4作为调用hypot函数的参数调用,结果为5
	fmt.Println(compute(math.Pow))  //将math.Pow函数作为compute函数的参数,使用3,4作为调用math.Pow函数的参数调用,结果为81
}

函数的闭包


package main

import "fmt"
func adder(i int) func(int) int {
	sum := i
	return func(x int) int {
		sum += x
		return sum
	}
}

func adder2(i int) func() int {
	sum := i
	return func() int {
		return sum
	}
}

func main() {
	fmt.Printf("%T\n", adder2(3))  //此处返回的类型为一个函数func() int
	fmt.Println(adder2(3)())       //使用此方式返回为最终的结果3
	
	pos, neg := adder(1), adder(1)
	for i := 0; i < 3; i++ {
		fmt.Println(
			pos(i),
			neg(-2*i),             //这里演示的也是闭包函数的调用方式,结果1 1,2 -1,4 -5
		)
	}
}



你可能感兴趣的:(golang)