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

时间:2017-05-10 08:54:58

标签: go error-handling string-formatting

这是我的计划。

package main

import (
    "errors"
    "fmt"
)

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

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

这是输出。

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

在这个程序中,我使用%s%v进行打印没有区别 error对象。

我有两个问题。

  1. 在打印出错误的地方是否有任何情况 %s%v的差异?
  2. 在这种情况下使用的格式说明符是什么?

1 个答案:

答案 0 :(得分:5)

According to docs

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

Also, more information about error

  

错误类型是接口类型。错误变量代表 any   可以将自己描述为字符串的值。

因此,请将其视为%s