-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
Add advice on formatting strings using %q
#186
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
# Format Strings Using `%q` | ||
|
||
Whenever formatting messages that contain a string component via `fmt`, use `%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. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
I'd either generalize these slightly or remove the word "error" (this guidance can apply to more than just errors). Maybe something like:
|
||
|
||
<table> | ||
<thead><tr><th>Bad</th><th>Good</th></tr></thead> | ||
<tbody> | ||
<tr><td> | ||
|
||
```go | ||
fmt.Errrof("file %s not found", filename) | ||
// Prints the following: | ||
// file myfile.go not found | ||
// | ||
// Or if the string is empty: | ||
// file not found | ||
``` | ||
|
||
</td><td> | ||
|
||
```go | ||
fmt.Errrof("file %q not found", filename) | ||
// Prints the following: | ||
// file "myfile.go" not found | ||
// | ||
// Or if the string is empty: | ||
// file "" not found | ||
``` | ||
|
||
</td></tr> | ||
</tbody></table> | ||
|
||
This advice applies more generally to other contexts when reporting user-specified data, such as logging invalid usernames: | ||
|
||
```go | ||
log.Printf("User %q does not exist", username) | ||
// User "no_name" does not exist | ||
``` | ||
Comment on lines
+33
to
+38
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would generalize this slightly to something like:
Mostly to avoid bucketing "logging" as "formatting" (i.e., structured logging - which is at least as relevant as I think the |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we might want to clarify slightly: it's not necessarily just when a string component in general is used, but more when dynamic strings (incl. user-provided values) could potentially cause interpolation to result in something weird.
Maybe something like: