golang 函数的特殊用法
发布时间:2020-12-16 09:25:44 所属栏目:大数据 来源:网络整理
导读:1.可以复用一些写法。经常在单元测试过程中需要new一些对象可以new的操作抽离出来 package mainimport "fmt"type S struct {}func (s *S) Service1(name string) { fmt.Println("Service 1",name)}func (s *S) Service2(name string) { fmt.Println("Service
1.可以复用一些写法。经常在单元测试过程中需要new一些对象可以new的操作抽离出来package main
import "fmt"
type S struct {
}
func (s *S) Service1(name string) {
fmt.Println("Service 1",name)
}
func (s *S) Service2(name string) {
fmt.Println("Service 2",name)
}
func (s *S) Service3(name string) {
fmt.Println("Service 3",name)
}
func newService() *S {
return &S{}
}
func withService(fn func(s *S)) func() {
return func() {
fn(newService())
}
}
func main() {
withService(func(s *S) {
s.Service1("first")
})()
withService(func(s *S) {
s.Service2("second")
})()
withService(func(s *S) {
s.Service3("third")
})()
}
2.中间件package main
import (
"fmt"
"time"
)
func work(name string) {
fmt.Println("hello ",name)
time.Sleep(time.Second)
}
func calTime(f func(name string)) func(string) {
t := time.Now()
return func(n string) {
defer func() {
fmt.Println("time spend is ",time.Since(t))
}()
f(n)
}
}
func main() {
s := calTime(work)
s("world")
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
