Apply select statement without case

From book I learn what the select statement can have form without case - select{}. That’s got to infinity wait. When apply this behaviour on practice?

Hey @GreyShatter,

You will rarely, if ever, actually need to use select{} by itself.

However, that being said, one simple example is If you were to have your main function simply executing other goroutines, main will normally just exit straight away if there’s no synchronization in place, although if synchronization is not needed and you just want main to block indefinitely, at least until you decide when to kill the program, select{} can be a simple one liner to place at the end of main to prevent it from exiting.

1 Like

A practical example. I want to run HTTP and HTTPS servers. I wrote the following code:

go func() {
    log.Fatal(http.ListenAndServeTLS(*enc, *cert, *key, mux))
}()

go func() {
    log.Fatal(http.ListenAndServe(*plain, red))
}()

select {}
1 Like

@grzegorz.zur , @radovskyb thanks for the explanation!

Why not just write

go func() {
    log.Fatal(http.ListenAndServeTLS(*enc, *cert, *key, mux))
}()

log.Fatal(http.ListenAndServe(*plain, red))

So we could do something before select{}.

go func() {
    log.Fatal(http.ListenAndServeTLS(*enc, *cert, *key, mux))
}()

go func() {
    log.Fatal(http.ListenAndServe(*plain, red))
}()

log.Printf("HTTP server listening on %s\n", *plain)
// ...

select {}

Why do you want to spin off the work in a goroutine then go to sleep forever? Why not just do the work in the current goroutine?

There is no point in doing it if I had just one call to ListenAndServe but since I have two calls I find it more readable to explicitly start two new goroutines and go to sleep. There is much more symmetry this way.

Here I would prefer two goroutines, both writing their err to a common error channel and then do a select on this error channel. In this case I can log it and os.Exit() the server. Otherwise one ending listener would still let the other one run (what surely could be another goal too :grin:).

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.