I'm trying to understand Go's interfaces and embedding.
What I'm trying to do here is create my own custom writer
and reader
where each one implements either io.Writer
or io.Reader
Now I want to take these custom structures that implement basic interfaces and embed them into another custom struct that implements Read/Write/Close
. The below code is what I have so far but when I run it I get the following error
cannot use test (type MyReadWriteCloser) as type io.Writer in argument to fmt.Fprintf:
MyReadWriteCloser does not implement io.Writer (missing Write method)
I thought when you embed a structure within another structure you also get the methods of the embedded structures. Can someone tell me what I'm missing?
package main
import (
"fmt"
"io"
)
type MyWriter struct {
w io.Writer
}
func (m MyWriter) Write(b []byte) (n int, err error) {
// encrypt b and write to underlying writer
m.w.Write(b)
return
}
type MyReader struct {
r io.Reader
}
func (m MyReader) Read(b []byte) (n int, err error) {
// decrypt b
m.r.Read(b)
return
}
type MyReadWriteCloser struct {
MyWriter
MyReader
}
func (m MyReadWriteCloser) Close() error {
return nil
}
func main() {
fmt.Println("main start")
r, w := io.Pipe()
test := MyReadWriteCloser{
MyWriter{w},
MyReader{r},
}
fmt.Fprintf(test, "hello world
")
}