Let's say I have the following function
func GetNumber() (*int, error) {
numb, err := getNumberFromDB(db)
if err != nil {
return nil, errors.New("error from db")
}
return numb, nil
}
numb is an *int, but the only situation in which it ever gets returned as nil, is if there is an error
So if I'm using GetNumber(), should I also be checking to see if int is nil prior to using it? It feels like I should to prevent future changes to GetNumber from causing issues (or maybe getNumberFromDB starts returning no error for some reason at some point).
But I also feel like it's very redundant and I'm adding these conditional checks everywhere. Just want to make sure I'm not following best practices.
IE:
numb, err : = GetNumber()
if err != nil {
//handle error
}
if numb == nil {
// this shouldn't happen
}
Another Example:
func EmailFromContext(ctx context.Context, key interface{}) (*string, error) {
ctxVal, ok := ctx.Value(key).(*validator.ValidatedClaims)
if !ok {
// so should this be returning "" instead of nil?
return nil, errors.New("could not convert claims")
}
return &claims.Email, nil
}