Occur in the processing of timeouts when issues:
Problem code
package main import( "fmt" "time" ) func main(){ var ch chan string go func() { ch <- "result" }() select { case res := <-ch: fmt.Println(res) return case <-time.After(time.Second * 5): fmt.Println("timeout") } }
Cause of the error: var ch chan string ch no allocation of space, so that has been running the case <- time.After (time.Second * 5) this branch. Solution is added: ch = make (chan string) or delete var ch chan string, add ch: = make (chan string)
Thinking:
var should make use of the pointer in a statement, chan, map when it allocated space, or can not use
Realization of comparative map:
var kl map[string]string kl["string"]="stk" fmt.Println(kl) //出现错误 var kt map[string]string kt = make(map[string]string) kt["string"] = "strin" fmt.Println(kt) //正确