在Go语言中,打印错误对象的正确格式说明符是`%v`。

huangapple go评论100阅读模式
英文:

What is the correct format specifier to print error object in Go: %s or %v?

问题

这是我的程序。

package main

import (
	"errors"
	"fmt"
)

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

func assertPositive(a int) error {
	if a <= 0 {
		return errors.New("断言失败")
	}
	return nil
}

这是输出结果。

错误:断言失败;整数:-1
错误:断言失败;整数:-1

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

我有两个问题。

  1. 在打印错误时,是否有任何情况下%s%v会有区别?
  2. 在这种情况下,应该使用哪个正确的格式说明符?
英文:

Here is my program.

package main

import (
	&quot;errors&quot;
	&quot;fmt&quot;
)

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

func assertPositive(a int) error {
	if a &lt;= 0 {
		return errors.New(&quot;Assertion failure&quot;)
	}
	return nil
}

Here is the output.

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

In this program, it makes no difference whether I use %s or %v to print
the error object.

I have two questions.

  1. Is there any scenario while printing errors where it would make a
    difference for %s and %v?
  2. What is the correct format specifier to use in this case?

答案1

得分: 41

根据文档:

%v	以默认格式显示值
...
%s	字符串或切片的未解释字节

此外,关于error的更多信息:

error类型是一个接口类型。error变量表示任何可以将自己描述为字符串的值

因此,将其视为%s

英文:

According to docs:

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

Also, more information about error:

> The error type is an interface type. An error variable represents any
> value that can describe itself as a string.

So, treat it as %s.

答案2

得分: 0

根据https://pkg.go.dev/fmt#Errorf,%w是正确的格式说明符。

英文:

%w is what is the correct format specifier according to https://pkg.go.dev/fmt#Errorf

huangapple
  • 本文由 发表于 2017年5月10日 16:54:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/43887776.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定