php editor Zimo, hello! Regarding the problem in the build error you mentioned, there may be several reasons for the "errors.As should not be error" error. First, this error usually means that the wrong second argument was used during the build. You need to make sure the second parameter is correct and matches the required type. Secondly, it could be that you are using the wrong data in your test. Please review your test data carefully and make sure they meet the expected format and requirements. Finally, this error can also be caused by issues with the framework or library. In this case, it is recommended to consult the relevant documentation or seek help from the community to find a solution. Hope these tips are helpful!
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 will return the build error second parameter to the error. Should not be *error
.
Go to the amusement park
However, when running the exact same code in main
, the program runs without issue:
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!" }
Go to the amusement park
I'm seeing this behavior in the go playground and in my local development environment, both using go 1.20.
Is this a bug in go?
I was able to solve the build failure issue in the test by creating the 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!" }
This error was reported by the go vet
command. The go test
command automatically runs go vet
to report critical issues. The go build
command does not run the go vet
command.
This warning is not a bug in Go.
Calling errors.As
with *error as the second argument makes no sense, since you already know that the first argument satisfies the error
interface. You're almost certainly doing something wrong.
The above is the detailed content of Why do I only receive the 'errors.As should not be *error' build error for the second parameter in my tests?. For more information, please follow other related articles on the PHP Chinese website!