In this article we will learn about some of the frequently asked GO programming questions in technical like “golang channel” Code Answer’s. When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. Error or stack handling on go was simple and easy. An error message with filename, line number and a message describing the error is sent to the browser. This tutorial contains some of the most common error checking methods in GO. Below are some solution about “golang channel” Code Answer’s.
go chanels
xxxxxxxxxx
1
ch := make(chan int) // create a channel of type int
2
ch <- 42 // Send a value to the channel ch.
3
v := <-ch // Receive a value from ch
4
5
// Non-buffered channels block. Read blocks when no value is available, write blocks until there is a read.
6
7
// Create a buffered channel. Writing to a buffered channels does not block if less than <buffer size> unread values have been written.
8
ch := make(chan int, 100)
9
10
close(ch) // closes the channel (only sender should close)
11
12
// read from channel and test if it has been closed
13
v, ok := <-ch
14
15
// if ok is false, channel has been closed
16
17
// Read from channel until it is closed
18
for i := range ch {
19
fmt.Println(i)
20
}
21
22
// select blocks on multiple channel operations, if one unblocks, the corresponding case is executed
23
func doStuff(channelOut, channelIn chan int) {
24
select {
25
case channelOut <- 42:
26
fmt.Println("We could write to channelOut!")
27
case x := <- channelIn:
28
fmt.Println("We could read from channelIn")
29
case <-time.After(time.Second * 1):
30
fmt.Println("timeout")
31
}
32
}
golang channel
xxxxxxxxxx
1
package main
2
3
import (
4
"encoding/json"
5
"fmt"
6
"runtime"
7
"time"
8
)
9
10
type Profile struct {
11
Name string `json:"name"`
12
Age uint `json:"age"`
13
}
14
15
func Publisher(data string, channel chan interface{}) {
16
channel <- string(data)
17
}
18
19
func Subscribe(channel chan interface{}) {
20
profile := <-channel
21
fmt.Println(profile)
22
}
23
24
func main() {
25
// set core max to use for gorutine
26
runtime.GOMAXPROCS(2)
27
28
// init compose type data
29
profileChannel := make(chan interface{})
30
31
// set value for struct
32
var profile Profile
33
profile.Name = "john doe"
34
profile.Age = 23
35
36
// convert to json
37
toJson, _ := json.Marshal(profile)
38
39
// sending channel data
40
go Publisher(string(toJson), profileChannel)
41
42
// get channel data
43
go Subscribe(profileChannel)
44
45
// delay gorutine 1000 second
46
time.Sleep(time.Second * 1)
47
}
48
golang make chan
xxxxxxxxxx
1
ch <- v // Send v to channel ch.
2
v := <-ch // Receive from ch, and
3
// assign value to v.