Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: errors: type constraint for As function #53129

Closed
prochac opened this issue May 28, 2022 · 3 comments
Closed

proposal: errors: type constraint for As function #53129

prochac opened this issue May 28, 2022 · 3 comments

Comments

@prochac
Copy link

prochac commented May 28, 2022

I propose small change to errors.As function.
To use type constraint for the second parameter.
func As[E error](err error, target *E) bool

What is the motivation?
Move a potential error from runtime to build time, even though it's being reported by go vet

second argument to errors.As must be a non-nil pointer to either a type that implements error, or to any interface type

Current any says nothing, the real constraint is described in documentation.

As will panic if target is not a non-nil pointer to either a type that implements error, or to any interface type. As returns false if err is nil.

Is is backward compatible change?
Yes and no.
In code, which doesn't follow documentation, it can lead to uncompilable code.
It has potential to crash in runtime, and is false in general.

Example:
https://go.dev/play/p/fhBlYngn_fQ

The synergy of errors.As and type constraints was already mentioned in early days of generics proposal.
https://go.googlesource.com/proposal/+/master/design/go2draft-error-inspection.md#The-Is-and-As-Functions

@gopherbot gopherbot added this to the Proposal milestone May 28, 2022
@changkun
Copy link
Member

Duplicate of #51945

@changkun changkun marked this as a duplicate of #51945 May 28, 2022
@prochac
Copy link
Author

prochac commented May 28, 2022

Actually, I saw these before I decided to propose this
#51945
#53045

They both propose API change.
Mine is not. Or is, partially, but not in the uncompatible way.

@seankhliao
Copy link
Member

Changing the signature of errors.As is an incompatible API change.

@golang golang locked and limited conversation to collaborators May 28, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants