Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在通道上迭代时写入Go文件IO失败_Go_Io_Channel_Goroutine - Fatal编程技术网

在通道上迭代时写入Go文件IO失败

在通道上迭代时写入Go文件IO失败,go,io,channel,goroutine,Go,Io,Channel,Goroutine,我有一个问题,写行到一个csv文件,而迭代通道。我是新手,但文件IO的语法在我看来是同步的。考虑到我期望一个写操作成功返回将表明写操作已完成,但这不是我所观察到的。这基本上就是我在应用程序中所做的: package main import ( "encoding/csv" "log" "os" ) func main() { file, err := os.Create("test.csv") if err != nil { log.F

我有一个问题,写行到一个csv文件,而迭代通道。我是新手,但文件IO的语法在我看来是同步的。考虑到我期望一个写操作成功返回将表明写操作已完成,但这不是我所观察到的。这基本上就是我在应用程序中所做的:

package main

import (
    "encoding/csv"
    "log"
    "os"
)

func main() {
    file, err := os.Create("test.csv")
    if err != nil {
        log.Fatalf("Error opening file: %s", err.Error())
    }
    defer file.Close()

    writer := csv.NewWriter(file)
    channel := make(chan []string)
    counter := 0

    go func() {
        defer close(channel)

        for i := 0; i < 100; i++ {
            channel <- []string{"col1", "col2"}
        }
    }()

    for vals := range channel {
        if err := writer.Write(vals); err != nil {
            log.Fatalf("Error writing to csv: %s", err.Error())
        }
        counter++
    }

    log.Printf("%d lines written", counter)
}
主程序包
进口(
“编码/csv”
“日志”
“操作系统”
)
func main(){
文件,err:=os.Create(“test.csv”)
如果错误!=零{
log.Fatalf(“打开文件%s时出错”,err.Error())
}
延迟文件。关闭()
writer:=csv.NewWriter(文件)
频道:=制作(chan[]字符串)
计数器:=0
go func(){
延迟关闭(通道)
对于i:=0;i<100;i++{

通道函数末尾缺少
writer.Flush()


更多信息

函数末尾缺少
writer.Flush()


更多信息

谢谢,伙计。我的头在墙上撞了很长时间。为什么它会在我的应用程序中写入一些内容到文件中?nvm,我在你发布的链接中看到了缓冲的部分。再次感谢。谢谢,伙计。我的头在墙上撞了很长时间。为什么它会将一些内容写入文件中在我的应用程序?nvm中,我看到了你发布的链接中关于缓冲的部分。再次感谢。