main.go:
xpackage main
import ( "context" "fmt" "time")
func main() { ticker := time.NewTicker(time.Second) chanInterface := make(chan interface{}, 100)
go func() { ctx := context.Background() ctx, cancelFunc := context.WithTimeout(ctx, 5*time.Second) defer cancelFunc()
for range ticker.C { select { // 写入一个整数 case chanInterface <- 1: // 写入一个字符串 case chanInterface <- "string": // 写一个布尔值 case chanInterface <- true: // 如果到达超时,那么关闭 Channel case <-ctx.Done(): fmt.Printf("Done") close(chanInterface) } } }()
for v := range chanInterface { switch v.(type) { case int: fmt.Printf("got integer %v\n", v.(int)) case string: fmt.Printf("got string %v\n", v.(string)) case bool: fmt.Printf("got bool %v\n", v.(bool)) } }
ticker.Stop()}运行若干次,观察输出。