go io_error ai_generated true

file already closed

ID: go/os-file-already-closed

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-02-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.13 active
1.14 active
1.15 active

Root Cause

Attempting to read, write, or close a file that has already been closed, often due to double-close or using a file after defer Close().

generic

中文

尝试对已关闭的文件进行读、写或关闭操作,通常是由于双重关闭或在 defer Close() 后使用文件。

Workarounds

  1. 95% success
    Use a sync.Once to ensure Close() is called only once.
  2. 90% success
    Set the file variable to nil after Close() and check for nil before using.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    The file pointer is not nil after closing; it's the underlying descriptor that is invalid.

  2. 60% fail

    Sync() does not prevent the file from being closed.