Golang / GoLang Basics Interview Questions
How does Go handle errors, and what is the difference between %v and %w in fmt.Errorf?
Go treats errors as values returned by functions, not as exceptions thrown from the call stack. This makes error handling explicit and visible. Every function that can fail returns an error as its last return value. The caller is responsible for handling it.
// error is a built-in interface: type error interface { Error() string }
// Standard pattern
func parseAge(s string) (int, error) {
age, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("parseAge: %w", err) // %w wraps the error
}
if age < 0 || age > 150 {
return 0, fmt.Errorf("parseAge: invalid age %d", age) // %v or plain
}
return age, nil
}
// Sentinel errors — compare with errors.Is()
var ErrNotFound = errors.New("not found")
// %w wraps the error — errors.Is / errors.As can inspect the chain
wrapped := fmt.Errorf("lookupUser: %w", ErrNotFound)
fmt.Println(errors.Is(wrapped, ErrNotFound)) // true
// %v formats as string — errors.Is CANNOT find original error
notWrapped := fmt.Errorf("lookupUser: %v", ErrNotFound)
fmt.Println(errors.Is(notWrapped, ErrNotFound)) // false!
// Custom error type
type ValidationError struct{ Field, Msg string }
func (e *ValidationError) Error() string {
return fmt.Sprintf("%s: %s", e.Field, e.Msg)
}
// errors.As — extract a specific error type from the chain
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Println("bad field:", ve.Field)
}
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...
