GO语言学习:单通道

1.单通道的应用价值

  约束其他代码行为,约束其他代码行为,约束其他代码行为

  1.函数的参数为单通道

  先看如下代码:

    func sendInt(ch chan <- int){

      ch<-rand.Intn(1000)

    }

  使用func关键字声明了一个sendInt的函数,这个函数只接受一个chan<-int类型的参数,在这个函数中我们只能向参数ch发送数据(通道为引用类型),而不能从他那里去取数据,这样就约束了代码的行为.

    type Notifier interface{

      sendInt(ch chan<-int)

    }

  Notifier接口中的方法sendInt只会接收一个发送通道作为参数,所以在该接口所有实现类型的sendInt方法都会受到限制,当然你也可以传一个通道进去,不过go会自动转为发送通道.

    intChan1:=make(chan int,2)

    sedInt(intChan1)

  2.函数声明的结果列表中使用单通道

    func getIntChan() <-chan int{

      num:=5

      ch:=make(chan int,num)

      for i:=0;i<num;i++{

        ch<-i

      }

      close(ch)

      return ch

    }

  getIntChan函数返回的是一个接收通道类型的通道,这意味着我们只能在此通道中接收数据.

    intChan2:=getIntChan()

    for elem:=rang intChan2{

      fmt.Printf("The element in intChan2 %v ",elem)

    }

  把函数的返回值赋给intChan2,然后用for语句循环去取数据,并打印出来.当intChan2中没有数据时就会被阻塞在那一行.如果为nil,则永远被阻塞在那一行.

2.select的用法

  在go中,select与c++的switch相似,但用法略有不同

    intChan:=make(chan int,1)

    select{

    case <-intChan:

    //todo

    default:

    //todo

    }  

    case只会执行一次,default为默认执行操作.每执行一个case会自动跳出,也可以自己使用break跳出select.

    在go中,select只和通道有关.

不为其他,只为快乐!
原文地址:https://www.cnblogs.com/1521299249study/p/10076204.html