go 闭包在外部函数调用的返回值

159 阅读1分钟
package main

import "fmt"

type ProtoMessage struct {
	value int
}

type Scope struct {
	pipelineUnmarshalFunc []func(int) *ProtoMessage
	keys                  []string
}

func (s *Scope) get(ret *ProtoMessage) {
	marshFuc := func(y int) *ProtoMessage {
		ret.value = y
		return ret
	}
	s.pipelineUnmarshalFunc = append(s.pipelineUnmarshalFunc, marshFuc)
	s.pipelineUnmarshalFunc = append(s.pipelineUnmarshalFunc, marshFuc)
	return
}

func (s *Scope) execPipe() {
	ret1 := s.pipelineUnmarshalFunc[0](10)
	fmt.Printf("%p\n", ret1)
	ret2 := s.pipelineUnmarshalFunc[1](20)
	fmt.Printf("%p\n", ret2)

	fmt.Println(ret1.value)
	fmt.Println(ret2.value)
	fmt.Println(ret1 == ret2) // 这里的结果是 true
}

func main() {
	protoMessage := &ProtoMessage{value: 0}
	s := &Scope{}
	s.get(protoMessage)
	s.execPipe()
}