Golang语法错误:在写入文件时遇到意外的EOF

huangapple go评论74阅读模式
英文:

Golang syntax error: unexpected EOF while writing to a file

问题

在代码的最后一行出现了syntax error: unexpected EOF的语法错误。这与文件IO有关,因为在添加这部分代码之前,JSON代码是可以正常工作的。

b, err := json.Marshal(gfjson)
if err != nil {
    panic(err)
}

filename := ".gfjson"

f, err := os.Create(filename)
if err != nil {
    panic(err)
}
// 在退出时关闭文件并检查返回的错误
defer func() {
    if err := f.Close(); err != nil {
        panic(err)
    }
}()

if _, err := f.Write(b); err != nil {
    panic(err)
}

fmt.Fprintf(os.Stdout, "GFJSON文件创建成功。\n")
英文:

Getting a syntax error: unexpected EOF on the last line of code which is a bracket. It has something to do with File IO because the JSON code worked before I added that in

b, err := json.Marshal(gfjson)
	if err != nil {
		panic(err)
	
	filename := ".gfjson"

	f, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	// close file on exit and check for returned error
	defer func() {
		if err := f.Close(); err != nil {
			panic(err)
		}
	}()

	
	if _, err := f.Write(b); err != nil {
		panic(err)
	}

	fmt.Fprintf(os.Stdout, "GFJSON file successfully created.\n")
}

答案1

得分: 1

你在第4行缺少一个闭合括号,应该在panic之后加上。

if err != nil {
    panic(err)
}

实际上,你的代码对我来说编译得很好,但这是因为你在末尾有一个随机的闭合括号来平衡它。根据你的缩进,我猜想末尾的闭合括号是你的函数的结束,只有panic应该是if语句的一部分。

英文:

You are missing a closing bracket on line 4 after the panic.

if err != nil {
    panic(err)
}

Your code actually compiles fine for me, but this is because you have a random closing brace at the end balancing it out. I assume from you indentations that the close brace at the end is then end of your function and only the panic should be part of the if statement.

huangapple
  • 本文由 发表于 2013年7月22日 11:40:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/17779587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定