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

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 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教