golang 函数的特殊用法

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")
}

猜你喜欢

转载自www.cnblogs.com/alin-qu/p/10927051.html