Skip to content

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

@yuxincs

Description

@yuxincs

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions