title: json.Marshal vs Encoder.Encode
body: <p>In the below code:</p>
  
  <pre><code>package main
  
  import (
      "bytes"
      "encoding/json"
      "fmt"
  )
  
  type Student struct {
      Firstname, lastname string
      Email               string
      Age                 int
      HeightInMeters      float64
      IsMale              bool
  }
  
  func main() {
      john := Student{
          Firstname:      "John",
          lastname:       "Doe",
          Age:            21,
          HeightInMeters: 1.75,
          IsMale:         true,
      }
  
      johnJSON, _ := json.Marshal(john) // johnJSON is of type []byte
      fmt.Println(string(johnJSON))     // print it in characters
  
  }
  </code></pre>
  
  <hr>
  
  <p><code>johnJSON, _ := json.Marshal(john)</code> is encoding a struct type(<code>john</code>) to <code>[]byte</code>.</p>
  
  <hr>
  
  <p>In the below code:</p>
  
  <pre><code>package main
  
  import (
      "bytes"
      "encoding/json"
      "fmt"
  )
  
  type Student struct {
      Firstname, lastname string
      Email               string
      Age                 int
      HeightInMeters      float64
      IsMale              bool
  }
  
  func main() {
      john := Student{
          Firstname:      "John",
          lastname:       "Doe",
          Age:            21,
          HeightInMeters: 1.75,
          IsMale:         true,
      }
  
      // johnJSON, _ := json.Marshal(john) // johnJSON is of type []byte
      // fmt.Println(string(johnJSON))     // print it in characters
  
      // create a buffer to hold JSON data
      buf := new(bytes.Buffer)
      // create JSON encoder for `buf`
      bufEncoder := json.NewEncoder(buf)
  
      bufEncoder.Encode(john)
      // print contents of the `buf`
      fmt.Println(buf) // calls `buf.String()` method
  }
  </code></pre>
  
  <hr>
  
  <p><code>bufEncoder.Encode(john)</code> is marshaling struct type(<code>john</code>) to <code>io.Writer</code> type(<code>buf</code>) </p>
  
  <hr>
  
  <p>When to use <code>json.Marshal()</code> vs <code>Encoder.Encode()</code>? Because both <code>buf</code> and <code>johnJSON</code> are <code>[]byte</code> type</p>
  
  <pre><code>type Buffer struct {
      buf      []byte // contents are the bytes buf[off : len(buf)]
      off      int    // read at &amp;buf[off], write at &amp;buf[len(buf)]
      lastRead readOp // last read operation, so that Unread* can work correctly.
  }
  </code></pre>