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 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名