How to implement Writer Interface


(Ajil Raju) #1

Please world give me some Write() function implementation from io.Writer.
with some example, it’s a confusing thing.


(Anik Hasibul) #2
var foo io.Writer
var bar = []byte("hello")
foo.Write(bar)

This will write the bytes to the io.Writer foo


(Jakob Borg) #3

Here’s a quick implementation that simply appends the written data to a slice.

func main() {
  w := &sliceWriter{}
  fmt.Fprintf(w, "hello")
  fmt.Fprintf(w, "world")
  // w.data is now []byte("helloworld")
}

type sliceWriter struct {
  data []byte
}

func (w *sliceWriter) Write(data []byte) (int, error) {
  w.data = append(w.data, data...)
  return len(data), nil
}

The beauty of this is that you can pass a *sliceWriter anywhere an io.Writer is expected, like fmt.Fprintf above. You can use it to debug your network connection by pairing a net.Conn (which is also an io.Writer) with a *sliceWriter using an io.MultiWriter, which is also an io.Writer. And so on. :slight_smile:


(Ajil Raju) #4

My confusion is not here, here we create the Write() method explicitly and where the io.Writer -> and the Write() method invocation


(Ignacio Gómez) #5

I’m not sure what you are trying to get to, but let’s assume it’s this: that’s the whole idea, you explicitly implement the method to implicitly implement the interface. Any struct that implements every method from an interface is then allowed to behave as that interface and, accordingly, be passed to a function that expects that kind of interface. I think Jakob showed it beautifully: it doesn’t matter what your implementation does (in his case, append to a slice), all Fprintf (the calling function in this case) needs to know is that your struct has the capabilities that any io.Witer has, i.e. the Write method, and thus will call the Write method on the passed argument. Of course, this is not the only case for interfaces, but again, it’s a great example.


(Cherolyn Lexvold) #6

When such an example is given, can I copy and paste it directly into the Go Playground? Because I’m getting this “prog.go:12:1: expected declaration, found foo” when I format it,
and this “./prog.go:12:1: syntax error: non-declaration statement outside function body” when I try to run it.