为什么不使用 %v 打印 int 和 string [英] Why not use %v to print int and string

查看:11
本文介绍了为什么不使用 %v 打印 int 和 string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know to print int we can use %d, and string we can use %s but we can still use %v to print them. So what if I always use %v to print them? What issue will happen if I do this?

推荐答案

不会有坏事发生,但是 %d 动词指示 fmt 包以数字形式打印(使用基数 10),%v 动词表示使用默认 可以被覆盖的格式.

Nothing bad will happen, but the %d verb instructs the fmt package to print is as a number (using base 10), and the %v verb means to use the default format which can be overridden.

看这个例子:

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 上试试):

Output (try it on the Go Playground):

2 *2*

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

When using the %v verb, the fmt package checks if the value implements the fmt.Stringer interface (which is a single String() string method), and if so, that method will be called to convert the value to string (which may be formatted further if flags are specified).

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

The complete list of formatting rules is in the package doc of fmt, quoting the relevant part:

除了使用动词 %T 和 %p 打印时,特殊格式注意事项适用于实现某些接口的操作数.按申请顺序:

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

  1. 如果操作数是 reflect.Value,则操作数将被它所持有的具体值替换,并按照下一条规则继续打印.

  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.

如果一个操作数实现了 Formatter 接口,它将被调用.Formatter 提供了对格式的精细控制.

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

如果 %v 动词与 # 标志 (%#v) 一起使用,并且操作数实现了 GoStringer 接口,则会调用该接口.

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

如果格式(对于 Println 等隐含 %v)对字符串 (%s %q %v %x %X) 有效,则适用以下两条规则:

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. 如果操作数实现了错误接口,则会调用Error方法将对象转换为字符串,然后根据动词的要求(如果有)进行格式化.

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

如果操作数实现方法 String() 字符串,将调用该方法将对象转换为字符串,然后根据动词(如果有)的要求对其进行格式化.

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

这篇关于为什么不使用 %v 打印 int 和 string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆