I'm still quite new to Go and I was surprised to not be able to use the subtype of an embedded interface. Here is a small example to explain what I mean:
func test(sl bufio.ReadWriter){
// cannot use sl(type bufio.ReadWriter) as type bufio.Reader in function argument
readStuff(sl)
[...]
writeStuff(sl) // same kind of error
}
func readStuff(sl bufio.Reader){
[...]
}
As every interface have the same memory layout and ReadWriter is a Reader and a Writer, I was expecting this code to work. I did try to convert the interface type with:
readStuff(sl.(buffio.Reader))
But it doesn't work either. So I've got two questions:
- Why doesn't it work?
- What's the go philosophy about that problem?
bufio.ReadWriter is a concrete type, not an interface. However, it does satisfy an interface (io.ReadWriter) so it can be assigned to a variable/function argument of an appropriate interface type. Then it works the way you may have anticipated (your code actually doesn't use any interfaces):
(Also here)
Output:
This way
test
can consume anyio.ReadWriter
, not only a specific one. Which is a hint towards your question about go "philosophy".They're different types. However, a
bufio.ReadWriter
contains a pointer to both abufio.Reader
type and abufio.Writer
type as elements of its struct. So passing the correct one should be easy enough. Try this: