Skip to content

Instantly share code, notes, and snippets.

@cv
Created Feb 12, 2020
Embed
What would you like to do?
shorten scope of intermediate variables
func (a *b) C(ctx context.Context) (*d, error) {
thingWithLongName, err := a.someService.Get(ctx, servicepkg.GetInput{
// …
})
if err == servicepkg.NotFound {
return &d{}, nil
}
if err != nil {
return nil, err
}
someIntermediaryThing := thingWithLongName.SomeProperty
thingIActuallyWant := someIntermediaryThing.ThingIActuallyWant
// bunch of junk left over in the scope, including `err` :(
}
func (a *b) C(ctx context.Context) (*d, error) {
var thingThatIActuallyWant *some.ObjType // pointers, please!
{
out, err := a.someService.Get(ctx, servicepkg.GetInput{
// …
})
if err == servicepkg.NotFound {
return &d{}, nil
}
if err != nil {
return nil, errors.Wrap(err, "could not get the thing from the service") // wrap errors
}
thingThatIActuallyWant := out.SomeProperty.SomeNestedProperty
}
// thingThatIActuallyWant is the only thing in scope now
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment