Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: prefer %q to format strings over %s #185

Open
yuxincs opened this issue May 26, 2023 · 1 comment · May be fixed by #186
Open

Proposal: prefer %q to format strings over %s #185

yuxincs opened this issue May 26, 2023 · 1 comment · May be fixed by #186

Comments

@yuxincs
Copy link

yuxincs commented May 26, 2023

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
@prashantv
Copy link
Contributor

+1, definitely want to encourage %q over %s, and possibly also encouraging using %q when reporting user-specified data like filenames in errors (vs no quotes).

@yuxincs yuxincs changed the title Proposal: prefer %q to format strings instead of %s Proposal: prefer %q to format strings over %s Jun 5, 2023
@yuxincs yuxincs linked a pull request Jun 5, 2023 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.

2 participants