1 // A buffered channel literal works for any element type, slice elements
2 // included.
3 //
4 // The defect this pins: the compiler rewrites `chan T{N}` / `chan T{:N}` source
5 // text into an internal allocation call before parsing. Two faults made a
6 // BUFFERED channel of a SLICE unbuildable:
7 //
8 // 1. the rewrite emitted __slicealloc(chan T, n) - the right builtin, since
9 // __slicealloc lowers to make() - but the SLICE rewrite ran first and ate
10 // the `[]byte{` inside `chan []byte{`, leaving `chan __slicealloc(...)`,
11 // which is not a type at all. Hence "cannot resolve the type of b ... the
12 // right-hand side is not a value".
13 // 2. nothing verified the CAPACITY, so an unbuffered channel would have passed
14 // a send/receive test just as well. The sends below happen before any
15 // receive: with capacity 0 they would deadlock the only thread.
16 package main
17 18 import (
19 "fmt"
20 "os"
21 )
22 23 func main() {
24 // Termination: a batch program must still be stoppable, so the entry
25 // handles the channel the runtime closes on SIGINT/SIGTERM.
26 select {
27 case <-shutdown:
28 return
29 default:
30 }
31 32 var fails int32
33 34 // Two sends with no receiver yet: only a buffered channel can hold them.
35 buf := chan []byte{:4}
36 buf <- []byte("hello")
37 buf <- []byte("world")
38 first := <-buf
39 second := <-buf
40 if string(first) != "hello" || string(second) != "world" {
41 fmt.Printf("FAIL slice chan: got [%s] [%s] want hello world\n", first, second)
42 fails = fails + 1
43 } else {
44 fmt.Printf("ok slice chan buffered and ordered\n")
45 }
46 47 // The same shape with a scalar element, and the unbuffered form.
48 nums := chan int32{:2}
49 nums <- 7
50 nums <- 9
51 a := <-nums
52 b := <-nums
53 if a != 7 || b != 9 {
54 fmt.Printf("FAIL int32 chan: got %d %d want 7 9\n", a, b)
55 fails = fails + 1
56 } else {
57 fmt.Printf("ok int32 chan buffered and ordered\n")
58 }
59 60 if fails != 0 {
61 fmt.Printf("chan_buffered_slice: %d wrong\n", fails)
62 os.Exit(1)
63 }
64 fmt.Printf("chan_buffered_slice ok\n")
65 }
66