check channel golang code example

Example 1: select channel golang

package main

import (
	"fmt"
)

func main() {
	c := make(chan int)

	go sender(c)
	receiver(c)
}

func sender(c chan<- int) {
	defer close(c)

	for i := 0; i < 10; i++ {
		c <- i
	}
}

func receiver(c <-chan int) {
	for {
		select {
		case v, ok := <-c:
			if !ok {
				return
			}
			fmt.Println(v)
		}
	}
}

Example 2: golang channel

package main

import (
	"encoding/json"
	"fmt"
	"runtime"
	"time"
)

type Profile struct {
	Name string `json:"name"`
	Age  uint   `json:"age"`
}

func Publisher(data string, channel chan interface{}) {
	channel <- string(data)
}

func Subscribe(channel chan interface{}) {
	profile := <-channel
	fmt.Println(profile)
}

func main() {
	// set core max to use for gorutine
	runtime.GOMAXPROCS(2)

	// init compose type data
	profileChannel := make(chan interface{})

	// set value for struct
	var profile Profile
	profile.Name = "john doe"
	profile.Age = 23

	// convert to json
	toJson, _ := json.Marshal(profile)

	// sending channel data
	go Publisher(string(toJson), profileChannel)

	// get channel data
	go Subscribe(profileChannel)

	// delay gorutine 1000 second
	time.Sleep(time.Second * 1)
}

Tags:

Go Example