Return a custom error without importing any package
Implement handle so it returns a non-nil error carrying the message "custom error". Constraint: you may not import any package — not even errors or fmt. Define your own error type.
func handle() error {
// your code here
}
Write the implementation.
error is a built-in interface with one method, Error() string. So you define a struct, give it an Error() string method, and return a pointer to it — no import needed. func (e *customError) Error() string { return "custom error" }, then return &customError{}. Any type implementing that one method satisfies error implicitly.
- ✗Thinking
errorlives in a package rather than being a built-in interface - ✗Believing
erroris an alias forstringthat you can cast to - ✗Expecting Go to auto-generate
Error()from a struct field
- →Why use a pointer receiver for
Error()rather than a value receiver here? - →How would adding fields to your error type let callers inspect it with
errors.As?
Solution
In Go, error is a built-in interface:
type error interface {
Error() string
}
Any type with an Error() string method satisfies it implicitly — nothing to import:
type customError struct{}
func (e *customError) Error() string {
return "custom error"
}
func handle() error {
return &customError{}
}
Returning &customError{} yields a non-nil error value. Because interface satisfaction in Go is implicit, neither errors nor fmt is needed here.
Adding fields lets you enrich the error with context and later inspect it with errors.As:
type customError struct{ Code int }
func (e *customError) Error() string {
return "custom error"
}