Go语言interface的value.(type)使用小技巧

前端之家收集整理的这篇文章主要介绍了Go语言interface的value.(type)使用小技巧前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. <pre name="code" class="plain">package main
  2.  
  3. import (
  4. "container/list"
  5. "fmt"
  6. "math/rand"
  7. "sync"
  8. "time"
  9. )
  10.  
  11. type INFO struct {
  12. lock sync.Mutex
  13. Name string
  14. Time int64
  15. }
  16.  
  17. var List *list.List = list.New()
  18.  
  19. func main() {
  20. var Info INFO
  21. go func() {
  22. for i := 0; i < 5; i++ {
  23. time.Sleep(time.Duration(1e9 * int64(rand.Intn(5))))
  24. Info.lock.Lock()
  25. Info.Name = fmt.Sprint("Name",i)
  26. Info.Time = time.Now().Unix() + 3
  27. Info.lock.Unlock()
  28. List.PushBack(Info)
  29. }
  30. }()
  31. go Getgoods()
  32. select {}
  33. }
  34. func Getgoods() {
  35. for {
  36. time.Sleep(1e8)
  37. for List.Len() > 0 {
  38. N,T := List.Remove(List.Front()).(INFO).name()
  39. now := time.Now().Unix()
  40. if T-now <= 0 {
  41. fmt.Println(N,T,now)
  42. continue
  43. }
  44. time.Sleep(time.Duration((T - now) * 1e9))
  45. fmt.Println(N,now)
  46. }
  47. }
  48. }
  49.  
  50. func (i INFO) name() (string,int64) {
  51. return i.Name,i.Time
  52. }

猜你在找的Go相关文章