文件类型如何作为读取器类型传递?

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

How *File type can be passed as Reader type?

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对golang还不熟悉。我看到了一个类似这样的golang代码:

file, err := os.Open("input.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

scanner := bufio.NewScanner(file)
...

根据文档,os.Open 返回 (*File, error) 类型,而 bufio.NewScanner(r) 的参数 rio.Reader 类型。

在上面的代码示例中,变量 file 的类型是 *File(指向 File 类型的指针),它可以传递给 bufio.NewScanner 方法,而该方法的参数期望的是 io.Reader 类型。这是如何可能的呢?

我查看了源代码,File 类型(https://golang.org/src/os/types.go?s=369:411#L6)和 io.Reader 类型(https://golang.org/src/io/io.go?s=3303:3363#L67)似乎没有关联。那么参数传递是如何可能的呢?

英文:

I'm new to golang. I saw a golang code like this:

file, err := os.Open("input.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

scanner := bufio.NewScanner(file)
...

According to the documentation, os.Open returns (*File, error) type, and bufio.NewScanner(r)'s argument r is having io.Reader type.

On the code example above, variable file which is having type of *File (pointer to File type) can be passed to bufio.NewScanner method which the argument is expectingio.Reader type. How could that possible?

I checked the source code, the File type (https://golang.org/src/os/types.go?s=369:411#L6), and io.Reader type (https://golang.org/src/io/io.go?s=3303:3363#L67) seems are unrelated. So how could the parameter passing is possible?

答案1

得分: 2

io.Reader 是一个接口,而 *os.File 实现了这个接口。在 Go Tour 中有对此进行了解释,我强烈推荐你去学习一下。

英文:

io.Reader is an interface, and *os.File implements the interface. It's explained in the Go Tour which I would highly recommend going through.

huangapple
  • 本文由 发表于 2017年7月11日 04:28:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/45021045.html
匿名

发表评论

匿名网友

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

确定