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

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?

图片转代码服务由CSDN问答提供 功能建议

通读“ Go编程语言”的7.8节,发现以下代码: \ n

  var err错误= syscall.Errno(2)
fmt.Println(err.Error())//“没有这样的文件或目录” 
fmt.Println(err)//“没有这样的文件 或目录“ 
   
 
 

我了解第一行和第二行。 error 接口由 syscall.Errno 处理,因此可以使用返回 string Error()函数。

我听不懂第三个。 通过 syscall 源< / a>我找不到 syscall.Errno 满足 stringer 接口的任何地方-未定义 String()函数。

为什么第三者打印 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
    
    点赞 评论

相关推荐 更多相似问题