What is the output of this Go program?
package main import ( "fmt" ) func main() { ch := make(chan string) go func() { ch <- "hello" }() msg := <-ch fmt.Println(msg) }
Think about how channels synchronize goroutines.
The goroutine sends "hello" to the channel. The main goroutine receives it and prints it. So the output is "hello".
What will this Go program print?
package main import ( "fmt" "time" ) func main() { ch1 := make(chan string) ch2 := make(chan string) go func() { time.Sleep(100 * time.Millisecond) ch1 <- "one" }() go func() { ch2 <- "two" }() select { case msg1 := <-ch1: fmt.Println(msg1) case msg2 := <-ch2: fmt.Println(msg2) } }
Which channel sends first without delay?
The goroutine sending to ch2 sends immediately, so select receives from ch2 first and prints "two".
What is the output of this Go program?
package main import ( "fmt" ) func worker(id int, ch chan<- string) { ch <- fmt.Sprintf("worker %d done", id) } func main() { ch := make(chan string) for i := 1; i <= 3; i++ { go worker(i, ch) } for i := 1; i <= 3; i++ { msg := <-ch fmt.Println(msg) } }
Order of output may vary but all workers send a message.
Each worker sends a message to the channel. The main goroutine receives all three messages and prints them. The order may vary but all three messages appear.
What does this Go program print?
package main import ( "fmt" ) func gen(nums ...int) <-chan int { out := make(chan int) go func() { for _, n := range nums { out <- n } close(out) }() return out } func sq(in <-chan int) <-chan int { out := make(chan int) go func() { for n := range in { out <- n * n } close(out) }() return out } func main() { c := gen(2, 3, 4) out := sq(c) for n := range out { fmt.Println(n) } }
Think about how data flows through the pipeline.
The gen function sends 2,3,4 to channel c. The sq function squares each number and sends it to out. The main prints 4,9,16.
What is the output of this Go program?
package main import ( "fmt" "sync" ) func main() { var counter int var wg sync.WaitGroup wg.Add(2) go func() { for i := 0; i < 1000; i++ { counter++ } wg.Done() }() go func() { for i := 0; i < 1000; i++ { counter++ } wg.Done() }() wg.Wait() fmt.Println(counter) }
Think about concurrent access to the variable without synchronization.
Because counter is incremented concurrently without locks, some increments are lost. The printed number is less than 2000 but varies.