Home > database >  In Go why can we use *os.File as a parameter in bufio.NewScanner when the definition suggests, it sh
In Go why can we use *os.File as a parameter in bufio.NewScanner when the definition suggests, it sh

Time:12-24

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.

CodePudding user response:

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)
  • Related