Using an indeterminate channel type

One trick that can often come in handy, and we haven't yet addressed, is the ability to have what is effectively a typeless channel.

If you're wondering why that might be useful, the short answer is concise code and application design thrift. Often this is a discouraged tactic, but you may find it useful from time to time, especially when you need to communicate one or more disparate concepts across a single channel. The following is an example of an indeterminate channel type:

package main

import (

  "fmt"
  "time"
)

func main() {

  acceptingChannel := make(chan interface{})

  go func() {

    acceptingChannel <- "A text message"
    time.Sleep(3 * time.Second)
    acceptingChannel <- false
  }()

  for {
    select {
      case msg := <- acceptingChannel:
        switch typ := msg.(type) {
          case string:
            fmt.Println("Got text message",typ)
          case bool:
            fmt.Println("Got boolean message",typ)
            if typ == false {
              return
            }
          default:
          fmt.Println("Some other type of message")
        }
        
      default:

    }

  }

  <- acceptingChannel
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.133.61