1 回答
![?](http://img1.sycdn.imooc.com/533e4c0500010c7602000200-100-100.jpg)
TA贡献1825条经验 获得超4个赞
您file1chan是无缓冲的,因此当您尝试通过该通道发送值时,它会永远阻塞,等待某人获取值。
您需要启动一个新的 goroutine,或者使通道缓冲并将其用作数组。这是带有另一个 goroutine 的版本:
func main() {
f, _ := os.Open("D:\\input1.txt")
scanner := bufio.NewScanner(f)
file1chan := make(chan string)
go func() { // start a new goroutine that sends strings down file1chan
for scanner.Scan() {
line := scanner.Text()
// Split the line on a space
parts := strings.Fields(line)
for i := range parts {
file1chan <- parts[i]
}
}
close(file1chan)
}()
print(file1chan) // read strings from file1chan
}
func print(in <-chan string) {
for str := range in {
fmt.Printf("%s\n", str)
}
}
这是缓冲版本,仅用于处理单个字符串:
func main() {
f, _ := os.Open("D:\\input1.txt")
scanner := bufio.NewScanner(f)
file1chan := make(chan string, 1) // buffer size of one
for scanner.Scan() {
line := scanner.Text()
// Split the line on a space
parts := strings.Fields(line)
for i := range parts {
file1chan <- parts[i]
}
}
close(file1chan) // we're done sending to this channel now, so we close it.
print(file1chan)
}
func print(in <-chan string) {
for str := range in { // read all values until channel gets closed
fmt.Printf("%s\n", str)
}
}
- 1 回答
- 0 关注
- 168 浏览
添加回答
举报