Golang How to view the length of unread data in channel channels

Source: Internet
Author: User

You can see the number of elements in the channel by using the built-in function Len.

The built-in function len is defined as follows:

Func len (v Type) int the Len built-in function returns the length of V, according to its Type:
Array:the number of elements in v. array of elements
Pointer to array:the numbers of elements in *v (even if v are nil). Number of elements in an array
Slice, or map:the number of elements in V; If V is nil and Len (v) is zero. The number of elements
String:the number of bytes in v. bytes
Channel:the Number of elements queued (unread) in the channel buffer; If V is nil, Len (v) is zero. The number of unread data in the channel

The following is a simple example of how to use it.

package mainimport "fmt"func main() {        c := make(chan int, 100)        fmt.Println("1.len:", len(c))        for i := 0; i < 34; i++ {                c <- 0        }                fmt.Println("2.len:", len(c))        <-c        <-c        fmt.Println("3.len:", len(c))}

Output

1.len:0
2.len:34
3.len:32

As you can see, after the definition, there is no element with a length of 0.
After writing 34 elements, the length is 34.
Finally, after reading two elements, the length becomes 32.

Reference

https://golang.org/pkg/builtin/#len

Golang How to view the length of unread data in channel channels

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.