A channel is created using chan keyword which allows to transfer data of the same type and it can be either sending or receiving. It does not allows to transmit different types of data from the same channel.
1 var <channel_name> chan <type>
Note : A channel can be created using make() function as a shorthand declaration as shown below without var keyword.
Create channel using make() function
1 <channel_name> := make(chan <type>)
1 package main
2
3 import "fmt"
4
5 func main() {
6
7
8 var channel1 chan int
9 fmt.Printf("Value of the channel1: %d", channel1)
10 fmt.Printf("\nType of the channel: %T ", channel1)
11
12
13 channel2 := make(chan int)
14 fmt.Printf("\nValue of the channel2: %d", channel2)
15 fmt.Printf("\nType of the channel1: %T ", channel2)
16 }
In the above example, we have created two channel using different ways, the first one using var keyword and the second is created using make function. It will value and the type data which will allows to transmit data.
1 Value of the channel1: 0
2 Type of the channel: chan int
3 Value of the channel2: 824633843904
4 Type of the channel1: chan int
Create channel and assigned value
Create channel and assigned value
1 package main
2
3 import "fmt"
4
5 func print(ch chan int) {
6
7 fmt.Println("Values from channel : ", <-ch)
8 }
9
10 func main() {
11
12
13 ch := make(chan int)
14
15
16 go print(ch)
17
18 fmt.Println("Value assigned to channel.")
19
20 ch <- 10
21 }
In the above example, a channel is created and bind with function as goroutine that will be called when value assigned to the channel. A value 10 is assigned to the channel, once a value assigned to channel, a print() goroutine will be called that access value assigned to the channel and print.
1 Value assigned to channel.
2 Values from channel : 10
Access channel value in multiple goroutine
Access channel value in multiple goroutine
1 package main
2
3 import "fmt"
4
5 func square(ch chan int) {
6 val := <-ch
7 fmt.Println("Square of value : ", val * val)
8 }
9
10 func cube(ch chan int) {
11 val := <-ch
12 fmt.Println("Cube of value : ", val * val * val)
13 }
14
15 func main() {
16
17
18 ch := make(chan int)
19
20
21 go square(ch)
22 ch <- 10
23
24 go cube(ch)
25 ch <- 2
26
27 fmt.Println("Program will be ended...")
28 }
In the above example, a channel is created and passed to the two goroutines. Once a channel value accessed or read, it is no more available in the channel. A value is added to channel which is accessed in square() goroutine that compute square and print. A second value is added to the channel which accessed in cube() that compute cube and print.
1 Square of value : 100
2 Cube of value : 8
3 Program will be ended...
Related options for your search