[Go实战]闭包实际使用

22 阅读1分钟
package main

import "fmt"

func main() {
	//闭包使用1
	Closure.test()
	//闭包使用2
	NewClosureService(&ClosureParameter{
		ParamFirst: 2,
	}).test()
}

var Closure = &ClosureService{}

type ClosureService struct {
	ClosureParam *ClosureParameter
}

type ClosureParameter struct {
	ParamFirst int //闭包参数
}

func (p *ClosureService) test() {
	if p.ClosureParam == nil {
		fmt.Println("你用了闭包的test方法")
	} else {
		fmt.Println("你用了闭包的test方法", p.ClosureParam.ParamFirst)
	}

}

func NewClosureService(closureParam *ClosureParameter) *ClosureService {
	return &ClosureService{
		ClosureParam: closureParam,
	}
}

输出结果: