在Go中打印错误对象的正确格式说明符是什么:%s或%v?

问题描述:

Here is my program.

package main

import (
    "errors"
    "fmt"
)

func main() {
    a := -1
    err := assertPositive(a)
    fmt.Printf("error: %s; int: %d
", err, a)
    fmt.Printf("error: %v; int: %d
", err, a)
}

func assertPositive(a int) error {
    if a <= 0 {
        return errors.New("Assertion failure")
    }
    return nil
}

Here is the output.

error: Assertion failure; int: -1
error: Assertion failure; int: -1

In this program, it makes no difference whether I use %s or %v to print the error object.

I have two questions.

  1. Is there any scenario while printing errors where it would make a difference for %s and %v?
  2. What is the correct format specifier to use in this case?

According to docs:

%v  the value in a default format
...
%s  the uninterpreted bytes of the string or slice

Also, more information about error:

The error type is an interface type. An error variable represents any value that can describe itself as a string.

So, treat it as %s.