douyueju2912 2017-05-10 08:54
浏览 250
已采纳

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

Here is my program.

package main

import (
    "errors"
    "fmt"
)

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

func assertPositive(a int) error {
    if a <= 0 {
        return errors.New("Assertion failure")
    }
    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条回答 默认 最新

  • dongyuji7309 2017-05-10 16:36
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于php中URL传递GET全局变量的问题
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件