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

Multi tool use
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:
bufio.NewScanner
io.Reader
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?
os.Stdin
os.File
os.Stdin
io.Reader
@Projjol
os.File
is a concrete type, your file
is a variable of that type, os.Stdin
is also a variable of that same type. io.Reader
is an interface type, the os.File
type implements the io.Reader
interface, therefore the values file
and os.Stdin
can be used as an argument to NewScanner.– mkopriva
23 mins ago
os.File
file
os.Stdin
io.Reader
os.File
io.Reader
file
os.Stdin
thanks @mkopriva
– Projjol
5 mins ago
thanks @Uvelichitel
– Projjol
4 mins ago
1 Answer
1
This is because bufio.NewScanner
has io.Reader
as an argument.
bufio.NewScanner
io.Reader
func NewScanner(r io.Reader) *Scanner
and io.Reader
is the interface that wraps the basic Read method.
io.Reader
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
.
*os.File
io.Reader
So whetever implements Reader interface can be passed as an argument to any method has io.Reader
as an argument.
io.Reader
thanks @Himanshu
– Projjol
3 mins ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
io.Reader is an interface. os.File and os.Stdin implement this interface having method Read() and can be used where io.Reader expected
– Uvelichitel
31 mins ago