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