You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
error is an interface type, possibly the most common return type, and yet it breaks this convention.
I think "Accept what you need" is a better first half, by which I mean accept the minium that you need. Here's a basic example with a constructor:
// New is bad because the caller has to have a file on disk but we don't actually need a file on disk.funcNew(fileNamestring) (Thing, error) {
input, err:=os.Open(fileName)
iferr!=nil {
returnfmt.Errorf("error opening input file: %w", err)
}
returnThing{i: input}, nil
}
// New is better because input can be in memory, or go:embed.funcNew(input io.Reader) (Thing, error) {
returnThing{i: input}, nil
}
// NewFromFile serves the original conveniencefuncNewFromFile(fileNamestring) (Thing, error) {
input, err:=os.Open(fileName)
iferr!=nil {
returnfmt.Errorf("error opening input file: %w", err)
}
returnNew(input)
}
This example does follow the convention, "Accept interfaces". But other examples exist with concrete types, like where you need a string vs []byte. The nugget of advice is to avoid things that look like conversion at the front of your function. "Accept only what you need"?
The return case is harder, if you can only return one concrete type then you should definitely do that, but if you might return one of several types then you must return an interface. Maybe you're returning what the caller needs? That's harder to predict. I've not found a good pithy phrase for this when I teach Go.
Activity
invidian commentedon Jun 24, 2022
Superseded by #37 maybe?
brackendawson commentedon Jun 12, 2025
Hands up if you've ever returned an error? ✋
error is an interface type, possibly the most common return type, and yet it breaks this convention.
I think "Accept what you need" is a better first half, by which I mean accept the minium that you need. Here's a basic example with a constructor:
This example does follow the convention, "Accept interfaces". But other examples exist with concrete types, like where you need a string vs []byte. The nugget of advice is to avoid things that look like conversion at the front of your function. "Accept only what you need"?
The return case is harder, if you can only return one concrete type then you should definitely do that, but if you might return one of several types then you must return an interface. Maybe you're returning what the caller needs? That's harder to predict. I've not found a good pithy phrase for this when I teach Go.