Hello World Goroutine

Download go eBook

Example

single channel, single goroutine, one write, one read.

package main

import "fmt"
import "time"

func main() {
    // create new channel of type string
    ch := make(chan string)

    // start new anonymous goroutine
    go func() {
        time.Sleep(time.Second)
        // send "Hello World" to channel
        ch <- "Hello World"
    }()
    // read from channel
    msg, ok := <-ch
    fmt.Printf("msg='%s', ok='%v'\n", msg, ok)
}

Run it on playground

The channel ch is an unbuffered or synchronous channel.

The time.Sleep is here to illustrate main() function will wait on the ch channel, which means the function literal executed as a goroutine has the time to send a value through that channel: the receive operator <-ch will block the execution of main(). If it didn't, the goroutine would be killed when main() exits, and would not have time to send its value.

Stats

Contributors: 4
2017-06-03
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook