Golang / GoLang Interfaces and Object Oriented Interview Questions
How does the io.Closer interface work with defer for resource management?
io.Closer is a single-method interface used to release resources. Combined with defer, it provides Go's idiomatic resource management pattern — analogous to try-with-resources in Java or RAII in C++.
// io.Closer definition
type Closer interface { Close() error }
// Pattern 1: defer immediately after acquiring the resource
func readConfig(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil { return nil, fmt.Errorf("open: %w", err) }
defer f.Close() // guaranteed to run when function returns
return io.ReadAll(f)
}
// Pattern 2: handle Close() error (important for writable files)
func writeConfig(path string, data []byte) (retErr error) {
f, err := os.Create(path)
if err != nil { return fmt.Errorf("create: %w", err) }
defer func() {
if err := f.Close(); err != nil && retErr == nil {
retErr = fmt.Errorf("close: %w", err) // capture Close error
}
}()
_, err = f.Write(data)
return err
}
// Pattern 3: implementing Closer on your own type
type DBPool struct {
pool *sql.DB
}
func (p *DBPool) Close() error { return p.pool.Close() }
// Closer in a function signature for maximum flexibility
func mustClose(c io.Closer) {
if err := c.Close(); err != nil {
log.Printf("close error: %v", err)
}
}
// Works for files, DB connections, HTTP response bodies, etc.Common mistake: not checking the error from Close() on a write path. For files opened for reading, Close() errors are usually harmless. For files opened for writing, Close() flushes buffered data to disk — an error here means data may be lost or corrupted and must be handled.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
