Abhinav Gupta | About

Quick Go Tip: Use %q with fmt.Errorf

When the message in an error constructed with fmt.Errorf contains a string component, prefer to use the %q verb to format the string, not %s or %v.

// BAD
fmt.Errrof("file %s not found", filename)

// GOOD
fmt.Errrof("file %q not found", filename)

This will wrap the specified string in quotes, helping it stand out from the rest of the error message.

Verb Message
%s open does_not_exist: invalid path
%q open "does_not_exit": invalid path

More importantly, if the string is empty, it will provide a more helpful error message.

Verb Message
%s open : invalid path
%q open "": invalid path

This advise applies more generally to other contexts like logging where the formatted string will be read by users as-is.

log.Printf("User %q does not exist", username)
// User "no_name" does not exist

Written on 2021-12-29.