AdSense

網頁

2021/9/23

Golang Channel 接收敘述 Receive statements

Go語言的Receive statements是指從channel接收/取出值的敘述。


例如下面從channel string型別的變數c接收值放入到變數s

s := <-c // receive value from channel c then assign to variable s

若channel中沒有值則gorouting會阻塞,直到有值送入channel後才會開始接收。

例如下面<-c的接收動作會阻塞,因為channel c的值在另一個goroutine中被time.Sleep()等待三秒後才被送入。

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("start")
    c := make(chan string) // create channel c

    go func() { // create goroutine to send value to c
        time.Sleep(3 * time.Second) // wait 3 second for this goroutine
        c <- "hello" // send "hello" to c
    }()

    fmt.Println(<-c) // receive "hello" from channel c
    fmt.Println("end")
}

若channel已經被關閉則會立刻執行(不阻塞),接收的值為channel元素型態的零值(zero value)。

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("start")
    c := make(chan string)

    go func() {
        time.Sleep(3 * time.Second)
        c <- "hello"
    }()
    close(c) // close channel c

    fmt.Println(<-c) // receive "" from channel c
    fmt.Println("end")
}

Channel的接收操作可多回傳一個boolean值表示是否成功接收來自發送端的值。若channel為空或關閉回傳false。

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("start")
    c := make(chan string)

    go func() {
        time.Sleep(3 * time.Second)
        c <- "hello"
    }()

    if s, ok := <-c; ok {
        fmt.Println(s)
    }
    fmt.Println("end")
}


沒有留言:

AdSense