【发布时间】:2016-09-07 16:36:15
【问题描述】:
我正在学习 GO。在学习了一些基础知识之后,我一直在尝试编写一个小程序,它可以使用 goroutines 将网页(切片中的 url)同时下载到不同的文件中。这是我写的一些代码:
func downloadFromUrl(url string) {
tokens := strings.Split(url, "/")
fileName := tokens[len(tokens)-1]
// I took out the bit that download the file for testing.
fmt.Println("Downloading", url, "to", fileName)
}
我注释掉了实际下载页面进行测试的部分。在我的主要功能中,我正在这样做:
func main() {
urls := []string{"http://www.google.com", "http://www.yahoo.com", "http://www.google.com"}
for _, url := range urls {
fmt.Println(url);
go downloadFromUrl(url);
}
}
问题是当我使用表达式go downloadFromUrl(url); 时,函数downloadFromUrl 没有运行。但如果我只是在循环中使用downloadFromUrl(url),它就可以正常工作。我究竟做错了什么?我必须在例程中使用通道吗?
【问题讨论】: