string - 为什么不使用 %v 打印 int 和 string

我知道打印 int 我们可以使用 %d,而 string 我们可以使用 %s 但我们仍然可以使用 %v 来打印它们。那么如果我总是使用 %v 来打印它们呢?如果我这样做会出现什么问题?

最佳答案

不会发生任何不好的事情,但是 %d 动词指示 fmt要打印的包是一个数字(使用基数 10),而 %v 动词表示使用可以覆盖的 default 格式。

看这个例子:

type MyInt int

func (mi MyInt) String() string {
    return fmt.Sprint("*", int(mi), "*")
}

func main() {
    var mi MyInt = 2
    fmt.Printf("%d %v", mi, mi)
}

输出(在 Go Playground 上尝试):

2 *2*

当使用 %v 动词时,fmt 包会检查该值是否实现了 fmt.Stringer接口(interface)(这是一个单一的 String() string 方法),如果是这样,该方法将被调用以将值转换为 string (如果标志可以进一步格式化已指定)。

完整的格式化规则列表在fmt的包文档中,引用了相关部分:

Except when printed using the verbs %T and %p, special formatting considerations apply for operands that implement certain interfaces. In order of application:

  1. If the operand is a reflect.Value, the operand is replaced by the concrete value that it holds, and printing continues with the next rule.

  2. If an operand implements the Formatter interface, it will be invoked. Formatter provides fine control of formatting.

  3. If the %v verb is used with the # flag (%#v) and the operand implements the GoStringer interface, that will be invoked.

If the format (which is implicitly %v for Println etc.) is valid for a string (%s %q %v %x %X), the following two rules apply:

  1. If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

  2. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

https://stackoverflow.com/questions/41159169/

相关文章:

html - 如何处理 XSLT 中嵌入的 XML 标记?

visual-studio - 使用标准格式将 Visual Studio 复制/粘贴到 Outlo

intellij-idea - Intellij 中的链式方法和连续缩进

javascript - 逗号优先的 JS 格式化程序

formatting - 突出显示重复值

c# - 格式化带有公制前缀的数字?

c# - 将零值格式化为空字符串?

objective-c - 本地化电话号码格式

r - 如何为 rmarkdown PDF 输出格式化复杂表格

html - 为什么 Visual Studio 格式文档工具将标题标签放在两行上?