title: io.Writer in Go - beginner trying to understand them
body: <p>As a beginner in Go, I have problems understanding <code>io.Writer</code>.  </p>
  
  <p>My target:  take a struct and write it into a json file.</p>
  
  <p>Approach:<br>
  - use <code>encoding/json.Marshal</code> to convert my struct into bytes<br>
  - feed those bytes to an <code>os.File</code> Writer</p>
  
  <p>This is how I got it working:</p>
  
  <pre><code>package main
  
  import (
      "os"
      "encoding/json"
  )
  
  type Person struct {
      Name string
      Age uint
      Occupation []string
  }
  
  func MakeBytes(p Person) []byte {
      b, _ := json.Marshal(p)
      return b
  }
  
  func main() {
      gandalf := Person{
          "Gandalf",
          56,
          []string{"sourcerer", "foo fighter"},
      }
  
      myFile, err := os.Create("output1.json")
      if err != nil {
          panic(err)
      }
      myBytes := MakeBytes(gandalf)
      myFile.Write(myBytes)
  }
  </code></pre>
  
  <p>After reading <a href="https://medium.com/@as27/a-simple-beginners-tutorial-to-io-writer-in-golang-2a13bfefea02" rel="noreferrer">this article</a>, I changed my program to this:</p>
  
  <pre><code>package main
  
  import (
      "io"
      "os"
      "encoding/json"
  )
  
  type Person struct {
      Name string
      Age uint
      Occupation []string
  }
  
  // Correct name for this function would be simply Write
  // but I use WriteToFile for my understanding
  func (p *Person) WriteToFile(w io.Writer) {
      b, _ := json.Marshal(*p)
      w.Write(b)
  }
  
  func main() {
      gandalf := Person{
          "Gandalf",
          56,
          []string{"sourcerer", "foo fighter"},
      }
  
      myFile, err := os.Create("output2.json")
      if err != nil {
          panic(err)
      }
      gandalf.WriteToFile(myFile)
  }
  </code></pre>
  
  <p>In my opinion, the first example is a more straightforward and easier to understand for a beginner... but I have the feeling that the 2nd example is the Go idiomatic way of achieving the target.  </p>
  
  <p>Questions:<br>
  1. is above assumption correct (that 2nd option is Go idiomatic) ?<br>
  2. Is there a difference in the above options ? Which option is better ?<br>
  3. other ways to achieve the same target ?  </p>
  
  <p>Thank you,</p>
  
  <p>WM</p>