英文:
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)
的参数 r
是 io.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论