gpt4 book ai didi

go - 在 Go : %s or %v? 中打印错误对象的正确格式说明符是什么

转载 作者:IT王子 更新时间:2023-10-29 01:25:51 27 4
gpt4 key购买 nike

这是我的程序。

package main

import (
"errors"
"fmt"
)

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

func assertPositive(a int) error {
if a <= 0 {
return errors.New("Assertion failure")
}
return nil
}

这是输出。

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

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

我有两个问题。

  1. 在打印错误时是否有任何情况会导致%s%v 有什么区别?
  2. 在这种情况下使用的正确格式说明符是什么?

最佳答案

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.

因此,将其视为%s

关于go - 在 Go : %s or %v? 中打印错误对象的正确格式说明符是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43887776/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com