我写了一个关于并发和通道⤵️的go代码
package main
import (
"fmt"
"net/http"
)
var links = []string{
"https://mcevik.com",
"https://stackoverflow.com",
"https://www.linkedin.com",
"https://github.com",
"https://medium.com",
"https://kaggle.com",
}
func getLink(link string, ch chan string) {
if res, err := http.Get(link); err != nil {
ch <- err.Error()
} else {
ch <- fmt.Sprintf("[%d] - %s", res.StatusCode, link)
}
}
func main() {
ch := make(chan string, len(links))
for _, link := range links {
go getLink(link, ch)
}
for msg := range ch {
fmt.Println(msg)
}
}
https://play.golang.org/p/Uz_k8KI6bKt
输出是这样的 ⤵️
在输出中,我们看到程序未终止。节目未终止的原因是通道尚未关闭,因此无法退出循环。
如何关闭通道并修复代码?
Cats萌萌
青春有我
温温酱
相关分类