//chan只能接收,无法发送
var uselessChan = make(chan<- int, 1)
uselessChan <-1
i:=<-uselessChan// invalid operation: <-uselessChan (receive from send-only type chan<- int)
fmt.Println(i)
//chan只能发送,无法接收
var uselessChan2 = make(<-chan int, 1)
j:=<-uselessChan2
fmt.Println(j)
uselessChan2 <-9//invalid operation: uselessChan2 <- 9 (send to receive-only type <-chan int)
for读取信道内容:
//返回值为单向通道
func main() {
intChan2 := getIntChan()
/**
for会一直尝试读取channel里面的值,如果 channel的值为nil,会阻塞在for关键字的一行
*/
for elem := range intChan2 {
fmt.Printf("The element in intChan2: %v\n", elem)
}
/**
The element in intChan2: 0
The element in intChan2: 1
The element in intChan2: 2
The element in intChan2: 3
The element in intChan2: 4
*/
}
func getIntChan() <-chan int {
num := 5
ch := make(chan int, num)
for i := 0; i < num; i++ {
ch <- i
}
close(ch)
return ch
}
如果在select语句中发现某个通道已关闭,那么应该怎样屏蔽掉它所在的分支?
func main() {
intChannels := make(chan int, 2)
intChannels <- 1
intChannels <- 2
for {
// 哪一个通道中有可取的元素值,哪个对应的分支就会被执行。
select {
case _,ok:=<-intChannels:
fmt.Println("The first candidate case is selected.")
if(!ok){
intChannels = make(chan int)
}
default:
fmt.Println("default.")
}
time.Sleep(time.Duration(2)*time.Second)
}
/**
输出结果:
The first candidate case is selected.
The first candidate case is selected.
default.
default.
default.
default.
*/
}
在select语句与for语句联用时,怎样直接退出外层的for语句?
func main() {
// 准备好几个通道。
intChannels := [3]chan int{
make(chan int, 2),
make(chan int, 2),
make(chan int, 2),
}
loop:
for {
// 随机选择一个通道,并向它发送元素值。
index := rand.Intn(3)
fmt.Printf("The index: %d\n", index)
intChannels[index] <- index
// 哪一个通道中有可取的元素值,哪个对应的分支就会被执行。
select {
case <-intChannels[0]:
fmt.Println("The first candidate case is selected.")
break loop
case <-intChannels[1]:
fmt.Println("The second candidate case is selected.")
case elem := <-intChannels[2]:
fmt.Printf("The third candidate case is selected, the element is %d.\n", elem)
default:
fmt.Println("default case is selected!")
}
}
fmt.Println("end")
}
/**
The index: 2
The third candidate case is selected, the element is 2.
The index: 0
The first candidate case is selected.
end
*/