Am learning Go
and here in this example, i can see that select
statement lets a goroutine wait on multiple communication operations
Do we really need a select
statement ? My below does the same without select
statement
func runForChannel1(channel1 chan string) {
time.Sleep(1 * time.Second)
channel1 <- "Hi Arun ... I am Channel-1"
}
func runForChannel2(channel2 chan string) {
time.Sleep(2 * time.Second)
channel2 <- "Hi Arun ... I am Channel-2"
}
func testSelect() {
channel1 := make(chan string)
channel2 := make(chan string)
go runForChannel1(channel1)
go runForChannel2(channel2)
chval1, chval2 := <-channel1, <-channel2
fmt.Println(chval1, chval2)
}
func main() {
testSelect()
}
Without the select
statment, i was able to wait for both the channels to get their values... Why we would need Select
statement ? Can someone educate me please ?
Do we really need a select statement ?
Yes. No user code can select exactly one of several possible channel operations if several are able to execute or none (default) if no case is ready.
(Your code does something completely different.)