go的接口和context的使用

先看下sort.Sort(data Interface),参数中Interface定义如下

type Interface interface {
   // Len is the number of elements in the collection.
   Len() int
   // Less reports whether the element with
   // index i should sort before the element with index j.
   Less(i, j int) bool
   // Swap swaps the elements with indexes i and j.
   Swap(i, j int)
}

如果我们想给结构体排序怎么办?只需要实现上面的三个接口即可,代码如下:

type Favors []Favor

type Favor struct {
   ID   int
   Name string
}

func (favors Favors) Len() int {
   return len(favors)
}

func (favors Favors) Less(i, j int) bool {
   favorLeft := favors[i]
   favorRight := favors[j]
   return favorLeft.ID < favorRight.ID
}

func (favors Favors) Swap(i, j int) {
   favors[i], favors[j] = favors[j], favors[i]
}

func main() {

   favors := []Favor{{ID: 2, Name: "123"}, {ID: 19, Name: "234"},{ID: 5, Name: "123"}, {ID: 3, Name: "234"},{ID: 4, Name: "123"}, {ID: 31, Name: "234"},{ID: 12, Name: "123"}, {ID: 21, Name: "234"}}

   sort.Sort(Favors(favors))

   for _, favor := range favors {
      fmt.Println(favor)
   }
}

另一种用法

type Favor struct {
   ID   int
   Name string
}
type customSort struct {
   favor []*Favor
   less  func(i, j *Favor) bool
}

func (custom customSort) Len() int {
   return len(custom.favor)
}

func (custom customSort) Less(i, j int) bool {
   return custom.less(custom.favor[i], custom.favor[j])
}

func (custom customSort) Swap(i, j int) {
   custom.favor[i], custom.favor[j] = custom.favor[j], custom.favor[i]
}

func main() {

   favors := []*Favor{{ID: 2, Name: "123"}, {ID: 19, Name: "234"}, {ID: 5, Name: "123"}, {ID: 3, Name: "234"}, {ID: 4, Name: "123"}, {ID: 31, Name: "234"}, {ID: 12, Name: "123"}, {ID: 21, Name: "234"}}

   sort.Sort(customSort{favors, func(i, j *Favor) bool {
      return i.ID < j.ID
   }})

   for _, favor := range favors {
      fmt.Println(favor)
   }
}

contextwithtimeout的使用,先来看一段代码

func slowOperation() {
   fmt.Println("slow operation start")
   time.Sleep(time.Second * 3)
   fmt.Println("slow operation end")

}
func operationTimeOut(ctx context.Context) {

   fmt.Println("operation time out start ")

   slowOperation()

   fmt.Println("operation time out end ")

}
func main() {
   fmt.Println("Program started ...")
   start := time.Now()

   ctx := context.Background()

   operationTimeOut(ctx)

   useTime := time.Since(start)
   fmt.Printf("Program end... It took %v seconds", useTime)
}

上面这段代码我们都能猜出结果

Program started ...
operation Time Out start 
slow operation start
slow operation end
operation Time Out end 
Program end... It took 3.000236344s seconds

这时候我们想用一个协程,设置一个超时时间,如果在那个时间内没有处理完就强制退出

func slowOperation() {
   fmt.Println("slow operation start")
   time.Sleep(time.Second * 3)
   fmt.Println("slow operation end")

}
func operationTimeOut(ctx context.Context) {

   fmt.Println("operation time out start ")

   signalChan := make(chan struct{})

   go func() {
      slowOperation()
      signalChan <- struct{}{}
   }()
   ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
   defer cancel()

   select {
   case <-signalChan:
      fmt.Println("task is succ")
   case <-ctx.Done():
      fmt.Println(ctx.Err())
   }

   fmt.Println("operation time out end ")

}
func main() {
   fmt.Println("Program started ...")
   start := time.Now()

   ctx := context.Background()

   operationTimeOut(ctx)

   useTime := time.Since(start)
   fmt.Printf("Program end... It took %v seconds", useTime)
}

输出如下:

Program started ...
operation time out start 
slow operation start
context deadline exceeded
operation time out end 
Program end... It took 1.00526883s seconds

发布了43 篇原创文章 · 获赞 37 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_28119741/article/details/89459891