Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "errors"
import "fmt"
type NotFound struct{ ID int }
func (e *NotFound) Error() string { return "not found" }
func main() {
var nf *NotFound
fmt.Println(errors.As(fmt.Errorf("load: %w", &NotFound{ID: 7}), &nf))
}true
- Expecting
false:errors.Aswalks the whole chain that%wbuilds, so it finds the*NotFoundinside the wrapper and stores it innf. - Expecting
&nfnot to compile:errors.Astakes the address of a variable of the type it looks for, here a pointer to a*NotFoundvariable.
- What would
errors.Is(err, &NotFound{ID: 7})return for the same wrapped error, and why? - What happens if you pass
nfinstead of&nftoerrors.As?