Skip to content

Commit

Permalink
feat: add select keyword
Browse files Browse the repository at this point in the history
  • Loading branch information
RealYukiSan committed Mar 15, 2023
1 parent 51b9431 commit 705c79b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
2 changes: 1 addition & 1 deletion main.go
Expand Up @@ -3,5 +3,5 @@ package main
import "explore-go/test"

func main() {
test.BufferedChannel()
test.SelectChannel()
}
48 changes: 48 additions & 0 deletions test/select_channel.go
@@ -0,0 +1,48 @@
package test

import (
"fmt"
"runtime"
)

func SelectChannel() {
runtime.GOMAXPROCS(2)

numbers := []int{3, 4, 3, 5, 6, 7, 8, 9, 3, 2}
fmt.Println("numbers :", numbers)
ch1 := make(chan float64)
go getAvarage(numbers, ch1)

ch2 := make(chan int)
go getMax(numbers, ch2)

for i := 0; i < 2; i++ {
select {
case avg := <-ch1:
fmt.Printf("Avg \t: %.2f \n", avg)

case max := <-ch2:
fmt.Printf("Max \t: %d \n", max)
}
}
}

func getAvarage(numbers []int, ch chan float64) {
sum := 0
for _, e := range numbers {
sum += e
}

ch <- float64(sum) / float64(len(numbers))
}

func getMax(numbers []int, ch chan int) {
max := numbers[0]
for _, e := range numbers {
if max < e {
max = e

}
}
ch <- max
}

0 comments on commit 705c79b

Please sign in to comment.