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?
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.