46 . Go - Channels - Directional
Making Directional Channels (Only Send OR Receive)
channel := make(chan string)
channel := make(<-chan string) // receive only, only can receive stuff from channel
channel := make(chan<- string) // send only, only can put stuff in channel
// Useful when declaring directional in functions.
Example:
package main
import "fmt"
func addTo(c chan<- string) {
c <- "MESSAGE"
fmt.Println("MESSAGE SENT")
}
func takeFrom(c <-chan string) {
fmt.Println("RECEIVED: ", <-c)
}
func main() {
channelOne := make(chan string)
go addTo(channelOne)
takeFrom(channelOne) // only runs after something is in channel because channel block
}
Comments
Post a Comment