我在此链接中看到了一些代码,并感到困惑:http : //www.darkcoding.net/software/go-lang-after-four- months/
第二个值(确定)是什么意思?
for self.isRunning { select { case serverData, ok = <-fromServer: // What's the meaning of the second value(ok)? if ok { self.onServer(serverData) } else { self.isRunning = false } case userInput, ok = <-fromUser: if ok { self.onUser(userInput) } else { self.isRunning = false } } }
接收操作符ok返回的布尔变量指示接收的值是在通道上发送的(true)还是由于通道关闭且为空而返回的零值(false)。
ok
for当Go程序的其他部分关闭fromServer或fromUser通道时,循环终止。在这种情况下,其中一个case语句将设置ok为true。因此,如果用户关闭连接或远程服务器关闭连接,程序将终止。
for
fromServer
fromUser
http://play.golang.org/p/4fJDkgaa9O:
package main import "runtime" func onServer(i int) { println("S:", i) } func onUser(i int) { println("U:", i) } func main() { fromServer, fromUser := make(chan int),make(chan int) var serverData, userInput int var ok bool go func() { fromServer <- 1 fromUser <- 1 close(fromServer) runtime.Gosched() fromUser <- 2 close(fromUser) }() isRunning := true for isRunning { select { case serverData, ok = <-fromServer: if ok { onServer(serverData) } else { isRunning = false } case userInput, ok = <-fromUser: if ok { onUser(userInput) } else { isRunning = false } } } println("end") }