How to implement Writer Interface

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

var foo io.Writer
var bar = []byte("hello")

This will write the bytes to the io.Writer foo


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")
  // is now []byte("helloworld")

type sliceWriter struct {
  data []byte

func (w *sliceWriter) Write(data []byte) (int, error) { = append(, 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:


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


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.


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.