Please, forgive me, I’m a newbee of learning golang, and there is one line code in golang source code, errors
package wrap.go
file. make me so confusing.
golang version: v1.22.5
;
package: errors
;
file name: wrap.go
;
code line: 53-78
;
func is(err, target error, targetComparable bool) bool {
for {
if targetComparable && err == target {
return true
}
// confusing line below
if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {
return true
}
// rest of lines
}
}
My confusing is:
- The
errors
package methoderrors.Is(err, target error) bool
has two parameters, how could it type assert to a anonymous interface with function which only have oneerror
parameters? - Is there any other exception allow such thing happen?
here is a example, I’m trying to verify.
James Buzzger is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
The line of code implements the following feature described in the errors.Is documentation:
An error type might provide an Is method so it can be treated as equivalent to an existing error. For example, if MyError defines
func (m MyError) Is(target error) bool { return target == fs.ErrExist }
then Is(MyError{}, fs.ErrExist) returns true.
The statement
if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {
return true
}
uses a type assertion to determine whether err
has an Is(error) bool
method. If err
has the method, then the method is called. If the method returns true, then errors.Is
returns true.
raygun is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
The
errors
package methoderrors.Is(err, target error) bool
has two parameters, how could it type assert to a anonymous interface with function which only have oneerror
parameters?
You’re right – it can’t! This isn’t trying to do anything with the errors.Is
function, it’s trying to check if err
implements it’s own way to determine if it is another error. From the dcoumentation:
An error type might provide an Is method so it can be treated as equivalent to an existing error. For example, if MyError defines
func (m MyError) Is(target error) bool { return target == fs.ErrExist }
then Is(MyError{}, fs.ErrExist) returns true.
The Is
function that the code you cite is looking for only has one parameter because the other parameter is replaced by the value that it is called on (err
).