英文:
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
这意味着它实现了由 io.Reader 接口提供的所有具有相同签名的方法。
在这种特定情况下,这个方法是:
func (f *File) Read(b []byte) (n int, err error)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论