I found the code snippet below on a tech talk, I am a little bit confused about one thing.
Should table <- new(Ball)
be placed before go player("ping", table)
?
And why do we even need table <- new(Ball)
? I think table := make(chan *Ball)
already creates the channel.
Has this something to do with deadlocks?
type Ball struct { hits int }
fun main() {
table := make(chan *Ball)
go player("ping", table)
go player("pong", table)
table <- new(Ball) // game on; toss the ball
time.Sleep(1*time.Second)
<-table // game over; grab the ball
}
func player(name string, table chan *Ball)
for {
ball := <-table
ball.hits++
fmt.println(name, ball.hits)
time.Sleep(100 * time.Millisecond)
table <- ball
}
}