您好:
參考
https://ithelp.ithome.com.tw/articles/10205301
package main
import (
"fmt"
)
var message chan string
func Bot() {
msg := <-message
fmt.Printf("Bot Print:%s\n", msg)
}
func main() {
//這裡為宣告 5 個 channel buffer,意思就是可以quene 5個 string
message = make(chan string, 5)
go Bot()
message <- "first message"
fmt.Println("first message send finish")
message <- "second message"
fmt.Println("second message send finish")
fmt.Println("end")
}
但結果,就算加了sleep
也只收到 fmt.Printf("Bot Print:%s\n", msg) 第一筆紀錄
其他都收不到??
請問這算正常嗎?
謝謝
// ithelp0707.go
// Craeted: 2020-07-07 22:35:39
// ---------------------
package main
import (
"fmt"
"time"
)
var message chan string
func Bot() {
for msg := range message {
fmt.Printf("Bot Print:%s\n", msg)
}
}
func main() {
message = make(chan string, 5)
go Bot()
message <- "first message"
fmt.Println("Main: first message send finish")
message <- "second message"
fmt.Println("Main: second message send finish")
time.Sleep(1 * time.Second)
fmt.Println("Main: end")
}
執行結果:
這裡有我以前寫的另外的範例.
https://ithelp.ithome.com.tw/articles/10158450?sc=pt
也可以這麼做
package main
import (
"fmt"
"time"
)
var message chan string
func Bot() {
for {
msg := <-message
fmt.Printf("Bot Print:%s\n", msg)
}
}
func main() {
//這裡為宣告 5 個 channel buffer,意思就是可以quene 5個 string
message = make(chan string, 5)
go Bot()
message <- "first message"
fmt.Println("first message send finish")
message <- "second message"
fmt.Println("second message send finish")
fmt.Println("end")
time.Sleep(5 * time.Second)
}
go Bot()照底下寫法
執行完 bot()就會完全結束
記得要加 for 讓他一直在執行中
(沒資料時,它會阻塞...也就是卡住,等待資料)
func Bot() {
msg := <-message
fmt.Printf("Bot Print:%s\n", msg)
}