Go, Channel Direction

Mike Code
1 min readJun 7, 2024

--

When we use a channel as a parameter in a function ,we can specify this channel is only used for sending message or receiving message.

package main

import (
"fmt"
"time"
)


func main() {
channel := make(chan string)
go sendMsg(channel, "hello")
go receiveMsg(channel)
time.Sleep(time.Second)
}

func sendMsg(ch chan <- string, msg string) {
ch <- msg
}
func receiveMsg(ch <- chan string) {
msg := <- ch
fmt.Println(msg)
}

We create a function sendMsg , this function take two parameters , first is a channel , but we add left arrow sign point from string type to chan ,it means this channel can only send data, we can’t use this channel to receive data .Second parameter is a string type msg. In function body we send this msg parameter’s value to this channel.

We create another function named receiveMsg, this function take one parameter is a channel, we add left arrow sign , it point from chan string to parameter, so it means this channel can only receive data, we can use this channel to send data.

In main function we create a channel to share string values. We call sendMsg function , pass channel we created before and a string value as arguments in a new goroutine. Then we call receiveMsg function in another goroutine, also pass the same channel as argument . Last we call sleep function from time, to block main goroutine to wait for sendMsg and receiveMsg function in other goroutines to finish .

When we run code , it will print hello.

--

--