Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 675
Projjol Avatar asked Oct 19 '25 07:10

Projjol


1 Answers

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.

like image 191
Himanshu Avatar answered Oct 20 '25 20:10

Himanshu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!