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: add AsTarget(error) #64629

Closed
mkielar opened this issue Dec 9, 2023 · 1 comment
Closed

proposal: errors: add AsTarget(error) #64629

mkielar opened this issue Dec 9, 2023 · 1 comment
Labels
Milestone

Comments

@mkielar
Copy link

mkielar commented Dec 9, 2023

Proposal Details

Proposal details

Add following function to errors package:

func AsTarget[T error](err T) **T {
	p1 := &err
	p2 := &p1
	return p2
}

Rationale

Currently, when using errors.As, one has to do some acrobatics to create a double pointer to the type of error they want to test. This usually leads to following constructs:

type MyErr struct{}
func (e *MyError) Error() string {return "foo"}

... 
var myErr *MyErr // this is bloat
if errors.As(err, &myErr) {
    ...
}

Everytime one wants to use errors.As they have to first define a variable, and then use that variable. With AsTarget in place, this would be a bit simpler:

...
if errors.As(err, AsTarget(MyErr)) {
    ...
}

I'm very new to go, and I don't really understand the reasons why errors.As couldn't just accept a zero-instance of a type. But since it is what it is, would you consider adding AsTarget to the standard library?

@gopherbot gopherbot added this to the Proposal milestone Dec 9, 2023
@seankhliao
Copy link
Member

Duplicate of #51945

@seankhliao seankhliao marked this as a duplicate of #51945 Dec 9, 2023
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Dec 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants