Channel Direction

  • This specificity increases the type-safety of the program.

in <-chan string 只允許 send to channel out chan<- string 只允許 receive from channel

func pong(in <-chan string, out chan<- string){}

exercises

https://go.dev/play/p/-pnSBwgi0YG

package main

import "fmt"

// Implement relaying of message with Channel Direction

func ping(out chan<- string) {
    // send message on ch1
    out <- "ping"
}

func pong(in <-chan string, out chan<- string) {
    // recv message on ch1
    msg := <-in
    msg = msg + "pong"

    // send it on ch2
    out <- msg
}

func main() {
    // create ch1 and ch2
    ch1 := make(chan string)
    ch2 := make(chan string)

    // spine goroutine genMsg and relayMsg
    go ping(ch1)
    go pong(ch1, ch2)

    // recv message on ch2
    msg := <-ch2
    fmt.Println(msg)
}
pingpong
© Kimi Tsai all right reserved.            Updated : 2023-07-12 09:04:54

results matching ""

    No results matching ""

    results matching ""

      No results matching ""