Projjol
Projjol

Reputation: 1375

Difference between os.File, io.Reader and os.Stdin

I was looking at NewScanner in the official go docs and it mentions the parameter to be passed to bufio.NewScanner should be of type io.Reader. However, the following works for me:

file, err := os.Open("filename")
scanner := bufio.NewScanner(file)

The same can be seen for os.Stdin as well. Given this what is the difference between os.File, os.Stdin and io.Reader ? Are they interchangeable?

Upvotes: 4

Views: 4027

Answers (1)

Himanshu
Himanshu

Reputation: 12675

This is because bufio.NewScanner has io.Reader as an argument.

func NewScanner(r io.Reader) *Scanner

and io.Reader is the interface that wraps the basic Read method.

type Reader interface {
        Read(p []byte) (n int, err error)
}

From the os package in Golang:

Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

func Open(name string) (file *File, err error)

The returned value *os.File implements io.Reader.

So whetever implements Reader interface can be passed as an argument to any method has io.Reader as an argument.

Upvotes: 4

Related Questions