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

时间:2022-05-04
本文章向大家介绍Go语言interface的value.(type)使用小技巧-转,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<pre name="code" class="plain">package main

import (
	"container/list"
	"fmt"
	"math/rand"
	"sync"
	"time"
)

type INFO struct {
	lock sync.Mutex
	Name string
	Time int64
}

var List *list.List = list.New()

func main() {
	var Info INFO
	go func() {
		for i := 0; i < 5; i++ {
			time.Sleep(time.Duration(1e9 * int64(rand.Intn(5))))
			Info.lock.Lock()
			Info.Name = fmt.Sprint("Name", i)
			Info.Time = time.Now().Unix() + 3
			Info.lock.Unlock()
			List.PushBack(Info)
		}
	}()
	go Getgoods()
	select {}
}
func Getgoods() {
	for {
		time.Sleep(1e8)
		for List.Len() > 0 {
			N, T := List.Remove(List.Front()).(INFO).name()
			now := time.Now().Unix()
			if T-now <= 0 {
				fmt.Println(N, T, now)
				continue
			}
			time.Sleep(time.Duration((T - now) * 1e9))
			fmt.Println(N, T, now)
		}
	}
}

func (i INFO) name() (string, int64) {
	return i.Name, i.Time
}