douzhi19900102 2018-11-27 08:32
浏览 377
已采纳

syscall.Errno中的字符串函数

Reading through the 7.8 section of "The Go Programming Language" I spotted following code:

var err error = syscall.Errno(2)
fmt.Println(err.Error()) // "no such file or directory"
fmt.Println(err)         // "no such file or directory"

I understand the first and second line. error interface is saitisfied by syscall.Errno, thus Error() function returning string is available.

I don't understand third one. Going through syscall's sources I can't find any place where syscall.Errno satisfies stringer interface - String() function is not defined.

Why third one prints string representation of sysscall.Errno?

  • 写回答

1条回答 默认 最新

  • douzhong3887 2018-11-27 08:39
    关注

    The answer is found in the fmt documentation here:

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

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

    So actually, for any value that supports both, the String() method is never called at all, since the error interface takes precidence over the Stringer interface. You can test this with a program like this one:

    package main
    
    import (
        "fmt"
    )
    
    type foo string
    
    func (f foo) String() string {
        return "string"
    }
    
    func (f foo) Error() string {
        return "error"
    }
    
    func main() {
        fmt.Println(foo(""))
    }
    

    Output:

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

报告相同问题?

悬赏问题

  • ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行
  • ¥15 资源泄露软件闪退怎么解决?
  • ¥15 各位佬,下面的问题怎么用python实现?
  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出