os.ErrClosed
GoERRORNotableFilesystem

file already closed

Quick Answer

Use errors.Is(err, os.ErrClosed) to detect use-after-close and audit your Close call sites.

What this means

Returned when an I/O operation is attempted on a file descriptor that has already been closed. Often indicates a double-close bug.

Why it happens
  1. 1Calling Close twice on the same file
  2. 2Reading or writing to a file after Close in a concurrent goroutine

Fix

Detect and log

Detect and log
if errors.Is(err, os.ErrClosed) {
    log.Println("BUG: operation on closed file")
}

Why this works

Detecting at the call site pinpoints the double-close location in the stack.

Code examples
Detectgo
_, err := f.Read(buf)
if errors.Is(err, os.ErrClosed) {
    fmt.Println("file closed")
}
Use sync.Once for closego
var once sync.Once
close := func() { once.Do(func() { f.Close() }) }
Defer single closego
f, _ := os.Open("x.txt")
defer f.Close()
// do not close again manually
Sources
Official documentation ↗

Go standard library

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Go errors