对golang goroutine、channel、select、reflect 温习一下,写了几个小例子
?
* 利用非 buff channel 和 goroutine 实现双goroutine 交易执行例子
``` type Ball struct { hits int } func player(name string, table chan *Ball) { for { ball := <-table ball.hits++ fmt.Println(name, ball.hits) time.Sleep(1 * time.Nanosecond) table <- ball } } func TestChannel(t *testing.T) { table := make(chan *Ball) go player("ping", table) go player("pong", table) table <- new(Ball) // game on; toss the ball time.Sleep(10 * time.Nanosecond) <-table // game over; grab the ball } ```
?
* 利用非buff channel单端读写阻塞特性灵活控制代码执行流程
``` func TestGoroutine(t *testing.T) { var ch = make(chan int) go func() { counter := <-ch for { counter++ fmt.Println("counter", counter) time.Sleep(1 * time.Nanosecond) } }() ch <- 0 start := time.Now().Nanosecond() time.Sleep(10 * time.Nanosecond) end := time.Now().Nanosecond() fmt.Println("cost-time", end - start) } ```
?
?
* 下面是一个select检测多个channel的实例
``` func TestSelect(t *testing.T) { a, b := make(chan string), make(chan string) go func() { a <- "a" }() go func() { b <- "b" }() b = nil for i := 2; i > 0; i-- { select { case s := <-b: fmt.Println("got", s) case s := <-a: fmt.Println("got", s) } } fmt.Println("finished") } ```
?
?
* 下面是一个通过反射构建struct,并通过json.Unmarshal 初始化struct的例子
``` type data struct { Title string Firstname, Lastname string Rank int } func TestAnonymousStruct(t *testing.T) { dValue := reflect.ValueOf(new(data)) dKind := dValue.Kind() if dKind == reflect.Ptr || dKind == reflect.Ptr { dValue = dValue.Elem() } fmt.Println("dValue", dValue) d1 := dValue.Interface() byteArray := bytes.NewBufferString(`{"Title":"title","Firstname":"firstName","Lastname":"lastname","Rank":1}`).Bytes() err := json.Unmarshal(byteArray, &d1) if nil != err { fmt.Println("d1 fill fail ") } fmt.Println(d1) } ```
?
? ?原文引自?http://threeperson.com/articles/2047
golang goroutine、channel、select、reflect
原文:http://zld406504302.iteye.com/blog/2264572