我知道打印 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:
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.
If an operand implements the Formatter interface, it will be invoked. Formatter provides fine control of formatting.
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:
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).
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/