Channel use of Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Channel

Sample1 Close twice

CH: = Make (chan bool) close (CH)  //This will panic, channel cannot close two times

The channel was closed early when it was read.

CH: = Make (Chan string) close (ch) I: = <-CH//will not panic, I read to the value is empty "",  if the channel is bool, then read to False

Write data to a channel that has been closed HTTP://PLAY.GOLANG.ORG/P/VL5D5TKFL7

CH: = Make (Chan string) Close (CH) ch <-"good"//Panic

Determine if the channel is close

I, OK: = <-chif OK {    println (i)} else {    println ("Channel Closed")}

For Loop Read Channel

For i: = range ch {//ch is closed, the For loop automatically ends    println (i)}

Prevent read Timeouts

Select {Case    <-time. After (time. second*2):        println ("read Channel timeout") Case    I: = <-ch:        println (i)}

Prevent write Timeouts HTTP://PLAY.GOLANG.ORG/P/AODFPNWDMJ

In fact, the read timeout is much like the select {case    <-time. After (time. Second):        println ("Write channel timeout") Case    ch <-"Hello":        println ("Write OK")}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.