Consider the following test:
import (
"errors"
"fmt"
"testing"
)
func TestError(t *testing.T) {
err := &MyError{}
var target error
fmt.Println(errors.As(err, &target))
}
type MyError struct{}
func (err *MyError) Error() string {
return "oops!"
}
Running this test returns the build error second argument to errors.As should not be *error
.
However, when running the exact same code in main
, then the program runs without issues:
package main
import (
"errors"
"fmt"
)
func main() {
err := &MyError{}
var target error
fmt.Println(errors.As(err, &target))
}
type MyError struct{}
func (err *MyError) Error() string {
return "oops!"
}
I am seeing this behavior in the Go Playground and my local development environment, both of which are using Go 1.20.
Is this a bug in Go?
I can work around the build failure in the test by creating an Error
type:
package main
import (
"errors"
"fmt"
"testing"
)
type Error error // <===== Add error type
func TestError(t *testing.T) {
err := &MyError{}
var target Error // <===== Use Error type
fmt.Println(errors.As(err, &target))
}
type MyError struct{}
func (err *MyError) Error() string {
return "oops!"
}
The error is reported by the go vet
command. The go test
command automatically runs go vet
to report significant problems. The go build
command does not run the go vet
command.
The warning is not a bug in Go.
There's no purpose in calling errors.As with a *error
as the second argument because you already know that the first argument satisfies the error
interface. You are almost certainly doing something wrong.