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 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64