Fragment Description:



The keyword to create and run a goroutine:
'go' A channel can be used as 'sending' or 'receiving' or 'both'.
A cute example.


makeCakeAndSend

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:30

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    "strconv"
    "time"
)

// channel is used as "sending only"
func makeCakeAndSend(channel chan<- string) {
    for i := 1; i <= 3; i++ {
        cakeName := "Strawberry Cake " + strconv.Itoa(i)
        fmt.Println("Making a cake and sending --->", cakeName)
        channel <- cakeName //send a strawberry cake
    }
}

// channel is used as "receiving only" channel
func receiveCakeAndPack(channel <-chan string) {
    for i := 1; i <= 3; i++ {
        s := <-channel //get whatever cake is on the channel
        fmt.Println("Packing received cake:\t", s)
    }
}
func main() {
    channel := make(chan string)
    // sending aspect of channel
    go makeCakeAndSend(channel)
    // receiving aspect of channel
    go receiveCakeAndPack(channel)
    // to have enough time to print... goroutines can be fast.
    time.Sleep(1e9)
}

/* Expected Output:
Making a cake and sending --->  Strawberry Cake 1
Packing received cake:         Strawberry Cake 1
Making a cake and sending --->  Strawberry Cake 2
Making a cake and sending --->  Strawberry Cake 3
Packing received cake:         Strawberry Cake 2
Packing received cake:         Strawberry Cake 3
*/



Comments