dtng25909 2018-07-26 09:55
浏览 539
已采纳

os.File,io.Reader和os.Stdin之间的区别

I was looking at NewScanner in the official go docs and it mentions the parameter to be passed to bufio.NewScanner should be of type io.Reader. However, the following works for me:

file, err := os.Open("filename")
scanner := bufio.NewScanner(file)

The same can be seen for os.Stdin as well. Given this what is the difference between os.File, os.Stdin and io.Reader ? Are they interchangeable?

  • 写回答

1条回答 默认 最新

  • douzhui8531 2018-07-26 10:05
    关注

    This is because bufio.NewScanner has io.Reader as an argument.

    func NewScanner(r io.Reader) *Scanner
    

    and io.Reader is the interface that wraps the basic Read method.

    type Reader interface {
            Read(p []byte) (n int, err error)
    }
    

    From the os package in Golang:

    Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

    func Open(name string) (file *File, err error)
    

    The returned value *os.File implements io.Reader.

    So whetever implements Reader interface can be passed as an argument to any method has io.Reader as an argument.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?