成都创新互联网站制作重庆分公司

Go中接口的类型查询:comma-ok断言和switch测试

// code_026_go_antic_package project main.go
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测试
网页路径:http://cxhlcq.com/article/pdjcde.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部