处理奇数和偶数

2022-11-23 19:15:57

package main

import (

"fmt"

)

func processOdd(inputs []int) chan int {

oddValues := make(chan int)

for _, numbers := range inputs {

go func(num int) {

if num%2 != 0 {

oddValues <- num

}

}(numbers)

}

return oddValues

}

func processEven(inputs []int) chan int {

evenValues := make(chan int)

for _, numbers := range inputs {

go func(num int) {

if num%2 == 0 {

evenValues <- num

}

}(numbers)

}

return evenValues

}

func main() {

inputs := []int{1, 17, 34, 56, 2, 8}

evenCH := processEven(inputs)

for range inputs {

fmt.Print(<-evenCH)

}

}

1 回答

HUH函数

TA贡献1531条经验 获得超1个赞

func processEven(inputs []int) chan int {

evenValues := make(chan int)

var wg sync.WaitGroup

for _, num := range inputs {

go func(num int) {

defer wg.Done()

if num%2 == 0 {

evenValues <- num

}

}(num)

}

go func() {

wg.Wait()

close(evenValues)

}()

return evenValues

}

func main() {

inputs := []int{1, 17, 34, 56, 2, 8}

evenCh := processEven(inputs)

for num := range evenCh {

fmt.Println(num)

}

}

• 1 回答
• 0 关注
• 8 浏览

0/150