有go有channal,slick,map,interface,func等等,其中func可以当作参数传递的这个功能也是很多动态语言支持的。
现在看下怎么使用
import (
"fmt"
)
type Do struct {
Name string
}
func (this Do) Lock() {
fmt.Println(this.Name + " Lock ...")
}
func (this Do) UnLock() {
fmt.Println(this.Name + " Unlock ~")
}
// 假设需要做加锁解锁
func Say() {
do := Do{Name: "Say"}
do.Lock()
defer do.UnLock()
fmt.Println("say doing")
}
// 假设需要做加锁解锁
func Fuck() {
do := Do{Name: "Fuck"}
do.Lock()
defer do.UnLock()
fmt.Println("fuck doing")
}
// 改造 -withContext
func withDoContext(fn func()) {
do := Do{Name: "do"}
do.Lock()
defer do.UnLock()
fn()
}
func Quit() {
withDoContext(func() {
fmt.Println("quit doing")
})
}
func Reboot() {
fmt.Println("reboot doing")
}
// 带有返回值的context
// 改造 -withContext
func withDoContextString(fn func() string) string {
do := Do{Name: "do"}
do.Lock()
defer do.UnLock()
return fn()
}
func main() {
fmt.Println("Start Main func()")
Say()
Fuck()
// 改造后
Quit()
withDoContext(Reboot)
msg := withDoContextString(func() string { return "hahah" })
fmt.Println("msg ", msg)
}
输出:
Start Main func()
Say Lock ...
say doing
Say Unlock ~
Fuck Lock ...
fuck doing
Fuck Unlock ~
do Lock ...
quit doing
do Unlock ~
do Lock ...
reboot doing
do Unlock ~
do Lock ...
do Unlock ~
msg hahah
有疑问加站长微信联系(非本文作者)