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

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort