receive a message from a channel in go

To receive a message from a channel in go, you can use the <- operator with the channel variable. This operator will block the current goroutine until a message is available in the channel. Here is an example:

main.go
package main

import "fmt"

func main() {
    ch := make(chan string)

    go func() {
        ch <- "Hello, World!" // send a message to the channel
    }()

    msg := <-ch // receive the message from the channel

    fmt.Println(msg) // print the message
}
260 chars
16 lines

In this example, we create a channel of type string using the make function. Then, we start a new goroutine that sends a message "Hello, World!" to the channel. Finally, we receive the message from the channel using the <- operator and print it out.

Note that if there are no messages available in the channel, the <- operator will block until a message is sent to the channel by another goroutine.

gistlibby LogSnag