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?
Edit
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!"
}