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

标签 string go formatting printf

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

最佳答案

没有什么不好的事情发生,但是 %d 动词指示 fmt要打印的包是一个数字(使用基数 10),%v 动词表示使用可以覆盖的默认格式。

看这个例子:

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).

关于string - 为什么不使用 %v 来打印 int 和 string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57942481/

相关文章:

r - 尝试获取 R 中的商作为数字对象

string - 什么是后缀自动机?

regex - 使用 Go Validator v2 转义正则表达式

c++ - 什么是 C+ +'s ` 在 golang 中使用`等价物

python - 如何为 python 中的所有 print() 输出设置前缀?

regex - 正则表达式用链接替换单词

c - 不明白为什么C程序崩溃,字符串指针数组

go - 访问 slice Golang模板中的struct中的特定字段

java - Spring AnnotationFormatterFactory 与 Thymeleaf th :text, 仅在字段显式为字符串时格式化

html - 在 FireFox 中格式化好,在 IE 中格式化不好....帮助