英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论