Golang / GoLang Interfaces and Object Oriented Interview Questions
How is the built-in error type defined and how do you implement custom errors?
The error type is Go's built-in interface for representing error conditions. It has exactly one method:
type error interface { Error() string }Any type that has an Error() string method satisfies the error interface. This makes error handling in Go extremely flexible — you can attach arbitrary context to errors by defining custom types.
// Simple sentinel errors
var ErrNotFound = errors.New("not found")
var ErrPermission = errors.New("permission denied")
// Structured custom error type
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation failed on %s: %s", e.Field, e.Message)
}
// Function returning the error interface
func validateAge(age int) error {
if age < 0 {
return &ValidationError{Field: "age", Message: "must be non-negative"}
}
if age > 150 {
return &ValidationError{Field: "age", Message: "unrealistically large"}
}
return nil // untyped nil — truly nil interface
}
// Inspect the error type with errors.As
err := validateAge(-1)
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Println("Field:", ve.Field, "Message:", ve.Message)
}
// Wrapped errors (Go 1.13+) — %w preserves the chain
func openConfig(path string) error {
if err := os.Open(path); err != nil {
return fmt.Errorf("openConfig %s: %w", path, err)
}
return nil
}
err = openConfig("/missing/config.yaml")
if errors.Is(err, os.ErrNotExist) {
fmt.Println("config file does not exist")
}
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...
