Abhinav Gupta | About

Go errors: Use %q with fmt.Errorf

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)

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


open does_not_exist: invalid path


open "does_not_exit": invalid path

More importantly, if the string is empty, it will provide a more helpful error message.

Verb Message


open : invalid path


open "": invalid path

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

Written on .