Return a meaningful value alongside an error when failure occurs. In Go, multiple returns let a function preserve its result contract instead of returning nil or an unusable placeholder. Check the error first; treating an empty result as the error signal creates ambiguity. section 4.1.1
Concatenating no strings
Concat returns an empty string and an error when called without parts, because an empty string is the expected string-shaped result when there is no data. Callers can inspect the error before using the result, and the function documents this error-case contract. section 4.1.1
Listing 4.3 Returning useful data with an error
func Concat(parts ...string) (string, error) {
if len(parts) == 0 {
return "", errors.New("No strings supplied") #1
}
return strings.Join(parts, " "), nil
}
Shows the complete multiple-return implementation, including the usable empty string and errors.New error. section 4.1.1
