In Go why can we use *os.File as a parameter in bufio.NewScanner when the definition suggests, it should only accept io.Reader?

huangapple go评论106阅读模式
英文:

In Go why can we use *os.File as a parameter in bufio.NewScanner when the definition suggests, it should only accept io.Reader?

问题

尝试学习Go语言,并使用bufio.NewScanner来读取文件内容。我使用以下代码来实现:

input_file, err := os.Open("input.txt")

if err != nil {
    panic(err)
}

scanner := bufio.NewScanner(input_file)
//处理文件内容

我查看了定义,发现了一些奇怪的地方(至少对我来说是奇怪的),上面的os.Open("input.txt")实际上返回的是*os.File,而bufio.NewScanner期望的是一个io.Reader作为参数。Reader是一个接口,而File是一个结构体,它并没有实现该接口或者其他类似的东西(如果可能的话)。

但是看起来这是完全可以的。我是否对Go的工作原理有所误解?我有C#的背景,对我来说,这两个参数是不同的类型,所以编译器不应该允许这样做,对吗?

我只是好奇,并不确定在哪里可以问这个问题。

英文:

Trying to learn Go and been using bufio.NewScanner to read contents of a file. I do this using the following code:

input_file, err := os.Open("input.txt")

if err != nil {
    panic(err)
}

scanner := bufio.NewScanner(input_file)
//do stuff

Thought I would look at the definition and saw something strange (well at least to me), os.Open("input.txt") above actually returns a *os.File and bufio.NewScanner expects a io.Reader as a parameter. Reader is an interface and File is a struct that does not implement the interface or anything like that if that's even possible.

But looks like this is totally fine. Am I missing something about how go works? I have a C# background and to me the parameters are of different types so the compiler shouldn't allow that, right?

Was just curious and wasn't sure where else to ask this.

答案1

得分: 2

os.File 实际上是实现了 io.Reader 接口。

这意味着它实现了由 io.Reader 接口提供的所有具有相同签名的方法。

在这种特定情况下,这个方法是:

func (f *File) Read(b []byte) (n int, err error)
英文:

os.File is actually implementing the io.Reader interface.

Which mean it implement all method with same signature provided by io.Reader interface.

In occurence in this particular case, this method:

func (f *File) Read(b []byte) (n int, err error)

huangapple
  • 本文由 发表于 2022年12月24日 13:47:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/74905812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定