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

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

Golang syntax error: unexpected EOF while writing to a file

问题

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

  1. b, err := json.Marshal(gfjson)
  2. if err != nil {
  3. panic(err)
  4. }
  5. filename := ".gfjson"
  6. f, err := os.Create(filename)
  7. if err != nil {
  8. panic(err)
  9. }
  10. // 在退出时关闭文件并检查返回的错误
  11. defer func() {
  12. if err := f.Close(); err != nil {
  13. panic(err)
  14. }
  15. }()
  16. if _, err := f.Write(b); err != nil {
  17. panic(err)
  18. }
  19. 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

  1. b, err := json.Marshal(gfjson)
  2. if err != nil {
  3. panic(err)
  4. filename := ".gfjson"
  5. f, err := os.Create(filename)
  6. if err != nil {
  7. panic(err)
  8. }
  9. // close file on exit and check for returned error
  10. defer func() {
  11. if err := f.Close(); err != nil {
  12. panic(err)
  13. }
  14. }()
  15. if _, err := f.Write(b); err != nil {
  16. panic(err)
  17. }
  18. fmt.Fprintf(os.Stdout, "GFJSON file successfully created.\n")
  19. }

答案1

得分: 1

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

  1. if err != nil {
  2. panic(err)
  3. }

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

英文:

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

  1. if err != nil {
  2. panic(err)
  3. }

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:

确定