Skip to content

Commit 9acf9fb

Browse files
committed
added channels
1 parent 5bac255 commit 9acf9fb

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

channels/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module channels
2+
3+
go 1.20

channels/main.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func sum(a, b int, result chan int) {
6+
result <- a + b
7+
}
8+
9+
func main() {
10+
// create a channel of type int.
11+
c := make(chan int)
12+
13+
// call goroutine using anonymous function.
14+
go func() {
15+
// send a value to the channel.
16+
c <- 10
17+
}()
18+
19+
// receive the value from the channel.
20+
v := <-c
21+
22+
// print the value.
23+
fmt.Println(v)
24+
25+
// pass the channel to function
26+
go sum(10, 20, c)
27+
28+
v = <-c
29+
fmt.Println(v)
30+
31+
// buffered channel with a capacity of 3
32+
ch := make(chan int, 3)
33+
34+
go func() {
35+
// send until the buffer is full
36+
// (non-blocking until it is full)
37+
ch <- 1
38+
ch <- 2
39+
ch <- 3
40+
}()
41+
42+
// receive as long as there's data in the buffer
43+
result1 := <-ch // No block
44+
result2 := <-ch // No block
45+
result3 := <-ch // No block
46+
47+
fmt.Printf("%d\n%d\n%d\n", result1, result2, result3) // Output: 1 2 3
48+
}

go.work

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
go 1.20
22

33
use (
4+
./channels
45
./datatypes
56
./deferfunc
67
./funcname

0 commit comments

Comments
 (0)