Sobes.tech
Senior

What are the ways to declare a WaitGroup? How to write a value into a channel?

sobes.tech AI

Answer from AI

WaitGroup declaration in Go:

var wg sync.WaitGroup
// or
wg := &sync.WaitGroup{}

WaitGroup is used to wait for a group of goroutines to finish. Main methods:

  • Add(n int) — increase the counter by n
  • Done() — decrease the counter by 1 (usually called in a goroutine)
  • Wait() — blocks execution until the counter becomes 0

Writing a value to a channel:

ch := make(chan int)

// Writing the value 42 to the channel
ch <- 42

If the channel is buffered, writing can be non-blocking if there is space in the buffer. If the channel is unbuffered, the write blocks until someone reads the value from the channel.