guide icon indicating copy to clipboard operation
guide copied to clipboard

Proposal: prefer `%q` to format strings over `%s`

Open yuxincs opened this issue 1 year ago • 1 comments

Note All credit goes to @abhinav

I learned this from one of @abhinav's amazing talks, and thought we could probably add this practice to this doc.

Whenever formatting messages that contain a string component via fmt, prefer %q instead of %s. This will wrap the specified string in quotes, helping it stand out from the rest of the error message. More importantly, if the string is empty, it will provide a more helpful error message.

BadGood
fmt.Errrof("file %s not found", filename)
// Prints the following: 
// file myfile.go not found
//
// Or if the string is empty:
// file not found
fmt.Errrof("file %q not found", filename)
// Prints the following:
// file "myfile.go" not found
//
// Or if the string is empty:
// file "" not found

yuxincs avatar May 26 '23 14:05 yuxincs