[2022-04-03]golang学习笔记

Learn about Office Tour

Function values is "C" like Callbacl

package main

import (
	"fmt"
)

func f1 (a int, callback func (x, y int) int) {
	fmt.Println("1111")
    callback(1,2)
}

func main() {
   //declare named function
	mycallback := func (x, y int)  int {
       x = y
		fmt.Println("---mycallback pass")
       return x*2
   }

   f1(100, mycallback)
	
   fmt.Println("gook")
}

go 1.8 支持,but go palyground is not good.

函数可以作为指针, 闭包closures

package main

import "fmt"

// adder 相当于函数指针
func adder() func(int) int {
	sum := 0
       // 闭包函数访问了sum变量,但是sum变量并不是func(x int)函数分配的
	return func(x int) int {
		sum += x
		return sum
	}
}

func main() {
	pos, neg := adder(), adder()
	for i := 0; i < 10; i++ {
		fmt.Println(
			pos(i),
			neg(-2*i),
		)
	}
}

function value
function closure

函数可以做值,函数闭包可以返回函数指针。 高级用法。
场景:

  1. 需要实现函数的回调效果,实现函数实现外挂注入,使用function value特性feature
  2. 闭包特性,实现了变量在当前函数体外申明,函数内调用,相当于函数的越界访问, what ?
    没有参数的引用传递,但是实现了变量引用传递的效果(能够修改变量的值)影响超出了自己的范围;
    包级package level 变量variable的变体。

Function closures

Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.

本地离线版标准库文档查看

go install golang.org/x/tools/cmd/godoc@latest
godoc -http=:3000
posted @ 2022-04-03 13:24  jiftle  阅读(50)  评论(0编辑  收藏  举报