Go語言程式用於檢測字串單向接收通道和整數傳送通道。


單向通道是一種只能用於接收或傳送資料的通道。在本文中,我們將建立一個Go語言程式來檢測一個包含字串的接收通道和一個包含整數的傳送通道。我們將學習如何使用單向通道來接收字串和使用無緩衝和緩衝通道、select語句以及使用結構體組合通道來發送整數。

語法

ch := make(chan string)

建立一個處理字串的通道。

ch <- "Hello, World!"

傳送字串值

message := <-ch

接收字串值

<-chan string

這表示字串的單向接收通道

演算法

  • 匯入 "fmt" 和 "sync" 包。

  • 定義 "processString" 和 "processData" 函式。

  • 在 "processData" 方法中使用 defer 語句來推遲對 wg.Done() 的呼叫。當 goroutine 完成時,這將通知 WaitGroup。

  • 使用 range 迴圈迭代從輸入通道 (in) 接收到的值。

  • 在主函式中建立一個名為 "input" 的輸入通道和一個名為 "output" 的輸出通道。

  • 建立一個名為 "wg" 的 WaitGroup,並將其計數器加 1。現在啟動 Goroutine

  • 並打印出已處理的值

示例 1:使用無緩衝通道

對於 goroutine 之間的通訊,無緩衝通道是一種有效的方法。透過使用無緩衝通道同步傳送方和接收方 goroutine 的操作,確保在傳送下一個值之前處理每個值。

package main

import (
   "fmt"
   "sync"
)

func processString(value string) int {
   return len(value)
}

func processData(in <-chan string, out chan<- int, wg *sync.WaitGroup) {
   defer wg.Done()

   for value := range in {
      processedValue := processString(value)

      out <- processedValue
   }
}

func main() {
   input := make(chan string)
   output := make(chan int)

   var wg sync.WaitGroup
   wg.Add(1) // Increment the WaitGroup counter

   go processData(input, output, &wg)

   go func() {
      defer close(input)

      input <- "123"
      input <- "456"
      input <- "789"
   }()

   go func() {
      defer close(output)

      for processedValue := range output {
         fmt.Println(processedValue)
      }
   }()

   wg.Wait()
}

輸出

3
3
3

示例 2:使用 select 語句

select 語句允許我們同時管理多個通道活動。select 語句確保程式繼續執行準備好處理的操作,從而避免不必要的等待時間。

package main

import (
   "fmt"
   "sync"
)
func processString(value string) int {

   return len(value)
}
func processData(in <-chan string, out chan<- int, wg *sync.WaitGroup) {
   defer wg.Done() 

   for value := range in {
      processedValue := processString(value)

      out <- processedValue
   }
}
func main() {
   input := make(chan string)
   output := make(chan int, 10) 

   var wg sync.WaitGroup
   wg.Add(1) 

   go processData(input, output, &wg)

   input <- "123"
   input <- "456"
   input <- "789"
   close(input)

   go func() {
      for processedValue := range output {
         fmt.Println(processedValue)
      }
   }()

   wg.Wait()

   close(output)
}

輸出

3
3
3

結論

在本文中,我們討論瞭如何編寫一個使用單向通道接收文字和傳送整數的程式。您可以透過 Go 的內建併發支援和通道輕鬆地在 goroutine 之間進行通訊,從而實現高效且併發的資料處理。

更新於:2023年7月5日

107 次瀏覽

啟動您的 職業生涯

完成課程後獲得認證

開始學習
廣告