Go中接口的類型查詢:comma-ok斷言和switch測試
阿新 • • 發佈:2018-10-06
ati UNC info plain 生成 表達 lis rand con
// code_026_go_antic_package project main.go
<pre name="code" class="plain">package main
import (
"container/list"
"fmt"
"math/rand" //備註2:隨機數的包
"sync" //備註1:異步任務的包
"time"
)
type INFO struct {
lock sync.Mutex //備註1:異步鎖
Name string
Time int64
}
var List *list.List = list.New() //備註3:初始化List變量
func main() {
var Info INFO
go func() {
for i := 0; i < 5; i++ {
time.Sleep(time.Duration(1e9 * int64(rand.Intn(5))))//備註2:隨機數rand.Intn(5)<---> 1e9為科學計數法,1 * 10的9次方
Info.lock.Lock()//備註1:上鎖
Info.Name = fmt.Sprint("Name", i) //備註: Sprint采用默認格式將其參數格式化,串聯所有輸出生成並返回一個字符串。如果兩個相鄰的參數都不是字符串,會在它們的輸出之間添加空格
Info.Time = time.Now().Unix() + 3
Info.lock.Unlock()//備註1:解鎖
List.PushBack(Info)//備註3:List表達式調用
}
}()
go Getgoods()
select {}
}
func Getgoods() {
for {
time.Sleep(1e8)
for List.Len() > 0 {//備註3:List對象的使用
N, T := List.Remove(List.Front()).(INFO).name() //備註3:List對象的使用和value.(type)的妙用
now := time.Now().Unix() //備註4:獲取當前日期轉換後的時間戳
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
}
Go中接口的類型查詢:comma-ok斷言和switch測試