Special function usage golang

1. You can reuse some of the wording. Often requires new testing unit of some new object can be pulled out of operation

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. Middleware

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

Guess you like

Origin www.cnblogs.com/alin-qu/p/10927051.html