1. What
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.Errorf("file %s not found", filename)
// GOOD
fmt.Errorf("file %q not found", filename)
2. Why
This will wrap the specified string in quotes, helping it stand out from the rest of the error message.
Verb | Message |
---|---|
|
|
|
|
More importantly, if the string is empty, it will provide a more helpful error message.
Verb | Message |
---|---|
|
|
|
|
3. Related
This advise also applies more generally to other contexts that use printf-style formatting where the formatted string is read by users as-is.
This includes, when you log messages with log.Printf
or
log.Fatalf
.
log.Printf("User %q does not exist", username)
// User "no_name" does not exist